简体   繁体   English

我将一些数据发送到Web服务,它以NSData返回一些JSON。 如何转换成Dict?(iOS 4.3)

[英]I send some data to a webservice, it returns some JSON as NSData. How to convert to Dict?(iOS 4.3)

I send some credentials to a web-service. 我将一些凭据发送到Web服务。

I can get the responce as NSData or as an NSString. 我可以将响应作为NSData或NSString来获取。

Whats the simpleist way to convert the (NSData or NSString)JSON to a NSDictionary so I can process it? 将(NSData或NSString)JSON转换为NSDictionary以便我可以处理的简单方法是什么?

Building for iOS4.3 Many Thanks, -Code 针对iOS4.3的构建非常感谢,-Code

From iOS 5.0 and on you can use NSJSONSerialization , docs here . 从iOS 5.0开始,您可以在此处使用NSJSONSerialization

There is a good tutorial on how to use it, here . 有关于如何使用它,一个很好的教程在这里

Use this : 用这个 :

NSString *urlString = [NSString stringWithFormat:kURLString,self.chapter,self.page];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:[urlString dataUsingEncoding:NSISOLatin1StringEncoding]];

NSData* responseData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSISOLatin1StringEncoding];


NSDictionary* result = [(NSDictionary*)[responseString JSONValue] objectForKey:@"Result"];

I use SBJson 我用SBJson

NSArray *arrObj = (NSArray*)[[JsonParser sharedJsonParser] getObjectsFromJsonString:responseString];

response string is a JSON string here 响应字符串是JSON字符串

Download SBJsonParser Framework using the link, http://github.com/stig/json-framework/downloads and add required classes to your project (SBJsonParser.h). 使用链接http://github.com/stig/json-framework/downloads下载SBJsonParser Framework,并将所需的类添加到项目(SBJsonParser.h)。

Import SBJsonParser.h and use the following code, 导入SBJsonParser.h并使用以下代码,

    SBJsonParser *parser = [[SBJsonParser alloc] init];

     //dictionary with name,id
     NSDictionary *jsonObject = [parser objectWithString:jsonString error:NULL];  

     //name array                
      NSMutableArray *nameArray = [[NSMutableArray alloc]init];
   for (NSMutableDictionary *dic in jsonObject){

      [nameArray addObject:[dic valueForKey:@"name"]];
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM