无法parsingJson到NSDictionary
我有一个WebService,它给了我下面的Json-String:
"{\"password\" : \"1234\", \"user\" : \"andreas\"}"
我打电话给web服务,并尝试parsing返回的数据,如:
[NSURLConnection sendAsynchronousRequest: request queue: queue completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error) { if (error || !data) { // Handle the error } else { // Handle the success NSError *errorJson = nil; NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &errorJson]; NSString *usr = [responseDict objectForKey:@"user"]; } } ];
但是由此产生的NSDictionary看起来像:
有什么影响,我不能得到的价值 – 例如用户。 有人可以帮助我,我做错了什么? – 谢谢。
从debugging器截图看来,服务器是(无论什么原因)返回“嵌套的JSON”: responseDict[@"d"]
是一个包含JSON数据的string,所以你必须应用两次NSJSONSerialization
:
NSError *errorJson = nil; NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData: data options:0 error: &errorJson]; NSData *innerJson = [responseDict[@"d"] dataUsingEncoding:NSUTF8StringEncoding]; NSMutableDictionary *innerObject = [NSJSONSerialization JSONObjectWithData:innerJson options:NSJSONReadingMutableContainers error:&errorJson]; NSString *usr = [innerObject objectForKey:@"user"];
如果您有select,更好的解决scheme是修复Web服务以返回适当的JSON数据。