Cannot parsing Json to NSDictionary

寵の児 提交于 2019-12-20 07:07:32

问题


I have a WebService, which give me the fallowing Json-String back:

"{\"password\" : \"1234\",  \"user\" : \"andreas\"}"

I call the webservice and try to parse the returned data like:

[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"];
        }
   }
 ];

But the resulting NSDictionary looks like:

What has the effect, that I cannot get the values - for example user. Can someone help me, what I am doing wrong? - Thank you.


回答1:


From the debugger screenshot is seems that the server is (for whatever reason) returning "nested JSON": responseDict[@"d"] is a string containing JSON data again, so you have to apply NSJSONSerialization twice:

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"];

If you have the option, a better solution would be to fix the web service to return proper JSON data.



来源:https://stackoverflow.com/questions/17283141/cannot-parsing-json-to-nsdictionary

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