Get the json which is in NSData

荒凉一梦 提交于 2019-12-11 00:35:30

问题


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)


来源:https://stackoverflow.com/questions/12396570/get-the-json-which-is-in-nsdata

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!