NSJSONSerialization 解析响应数据
我创建了一个 WCF 服务,它为我的 POST 操作提供以下响应:
"[{\"Id\":1,\"Name\":\"Michael\"},{\"Id\":2,\"Name\":\"John\"}]"
我对 JSONObjectWithData 的调用没有返回任何错误,但我无法枚举结果,我做错了什么?
NSError *jsonParsingError = nil;
NSMutableArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&jsonParsingError];
NSLog(@"jsonList: %@", jsonArray);
if(!jsonArray)
{
NSLog(@"Error parsing JSON:%@", jsonParsingError);
}
else
{
// Exception thrown here.
for(NSDictionary *item in jsonArray)
{
NSLog(@"%@", item);
}
}
I created a WCF service, which provides the following response to my POST operation:
"[{\"Id\":1,\"Name\":\"Michael\"},{\"Id\":2,\"Name\":\"John\"}]"
My call to JSONObjectWithData, doesn't return any error, yet I can't enumerate over the results, what am I doing wrong?
NSError *jsonParsingError = nil;
NSMutableArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&jsonParsingError];
NSLog(@"jsonList: %@", jsonArray);
if(!jsonArray)
{
NSLog(@"Error parsing JSON:%@", jsonParsingError);
}
else
{
// Exception thrown here.
for(NSDictionary *item in jsonArray)
{
NSLog(@"%@", item);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如 Jeremy 指出的,您不应该转义 JSON 数据中的引号。而且,您还引用了返回字符串。这使得它成为一个 JSON 字符串,而不是一个对象,所以当你解码它时,你得到的是一个字符串,而不是一个可变数组,这就是为什么当你尝试快速迭代时会收到错误......你无法快速迭代字符串。
您的实际 JSON 应如下所示:
[{"Id":1,"Name":"Michael"},{"Id":2,"Name":"John"}]
。没有引用,没有逃避。一旦消除了 JSON 对象周围的引号,您的应用程序就不会再崩溃,但随后您将收到格式错误的数据(转义)的 JSON 反序列化错误。As Jeremy pointed out, you shouldn't escape the quotes in the JSON data. But also, you've quoted the return string. That makes it a JSON string, not an object, so when you decode it you've got a string, not a mutable array, which is why you get an error when you try to fast iterate... you're not able to fast iterate over a string.
Your actual JSON should look like:
[{"Id":1,"Name":"Michael"},{"Id":2,"Name":"John"}]
. No quotes, no escapes. Once you eliminate the quotes around your JSON object, your app won't crash anymore, but then you're going to get a JSON deserialization error for malformed data (the escapes).可能的原因是您使用了错误的基础对象。尝试将 NSMutableArray 更改为 NSDitonary。
发件人:
收件人:
The likely cause is you are using the wrong foundation object. Try changing NSMutableArray to NSDictonary.
From:
To:
使用 NSJSONSerialization 进行解析很简单,但我还创建了一个小框架,允许将 JSON 值直接解析为类对象,而不用处理字典。看一下,可能会有所帮助:
https://github.com/mobiletoly/icjson
Parsing with NSJSONSerialization is easy, but I have also created a little framework that allows parsing JSON values directly into class objects, instead of dealing with dictionaries. Take a look, it might be helpful:
https://github.com/mobiletoly/icjson