无法将Json解析为NSDictionary [英] Cannot parsing Json to NSDictionary
问题描述
我有一个WebService,它让我退回Json-String:
I have a WebService, which give me the fallowing Json-String back:
"{\"password\" : \"1234\", \"user\" : \"andreas\"}"
我调用webservice并尝试解析返回的数据,如:
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"];
}
}
];
但是得到的NSDictionary看起来像:
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.
推荐答案
从调试器截图看来,服务器(无论出于何种原因)返回
嵌套的JSON: responseDict [@d]
是一个包含JSON数据的字符串,所以你需要
apply NSJSONSerialization
两次:
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"];
如果您有选择,更好的解决方案是修复Web服务以返回
适当的JSON数据。
If you have the option, a better solution would be to fix the web service to return proper JSON data.
这篇关于无法将Json解析为NSDictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!