Get the json which is in NSData

2019-07-21 07:10发布

问题:

I'm new in Objective-c. I want to make an HTTPRequest to an API. This works, I get my response in an NSData object. This response is a json response. How can I parse my response to get a dictionary with key: value format?

I used this code to get the data:

  data = [NSURLConnection sendSynchronousRequest: req
                             returningResponse: nil
                                         error: nil];

Thanks

回答1:

Use NSJSONSerialization (iOS5+) to convert JSON strings to Cocoa objects (NSDictionary in your case) and vice-versa.

PS : If you need to also support iOS versions before 5.0, namely where the NSJSONSerialization is not available, there are third-party libraries out there, like JSONKit for example. You may then either always use JSONKit both on iOS4 and iOS5, or your may test at runtime for NSJSONSerialization availability and use it if available (but fallback to JSONKit if not).

(For more details on cross-SDK development, like making and app compatible with iOS4 but being able to use iOS5 classes when available, see the SDK Compatibility Guide)


By the way, you should (must) avoid using synchronous URL requests. This will block your thread until it receives the response from the network. If you execute it on the main thread, your whole UI will be frozen until you receive the response, which can take several seconds in a mobile environment (where you don't always have the best network coverage).

Prefer:

  • using the API of NSURLConnection that uses a delegate (See the URL Loading System Programming Guide for details),
  • or using the newly introduced sendAsynchronousRequest:queue:completionHandler: method (iOS5+) that will execute the request in a background NSOperation,
  • or use some third-party framework that will make your work with requests easier (I recommend AFNetworking for that, which is also great for communicating with WebServices and automatically convert the response to a JSON object, uses blocks to handle the response asynchronously and make your code easier to write and understand, and much more)