获取NSData中的json [英] Get the json which is in NSData
问题描述
我是Objective-c的新手.我想对API发出HTTPRequest.这行得通,我在NSData对象中得到了响应.这个回应是json响应.我如何解析我的回复以获得字典与键:值格式?
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];
谢谢
推荐答案
Use NSJSONSerialization (iOS5+) to convert JSON strings to Cocoa objects (NSDictionary
in your case) and vice-versa.
PS:如果您还需要支持5.0之前的iOS版本,即在 NSJSONSerialization
不可用的地方,则存在第三方库,例如
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).
(有关跨SDK开发的更多详细信息,例如与iOS4兼容的应用程序以及与之兼容的应用程序,但能够在可用时使用iOS5类,请参见顺便说一句,您(必须)避免使用同步URL请求.这将阻塞您的线程,直到它接收到来自网络的响应.如果您在主线程上执行它,则整个UI将被冻结,直到收到响应为止,这在移动环境(网络覆盖范围并不总是最佳)中可能要花费几秒钟.
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).
首选:
- 使用使用委托的NSURLConnection的API(请参见 AFNetworking 用于这对于与WebServices进行通信并自动将响应转换为JSON对象也非常有用,它使用块异步处理响应,并使您的代码更易于编写和理解,等等)
- 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)
这篇关于获取NSData中的json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!