NSJSONSerialization解析响应数据 [英] NSJSONSerialization parsing response data
问题描述
我创建了一个WCF服务,它为我的POST操作提供以下响应:
I created a WCF service, which provides the following response to my POST operation:
"[{\"Id\":1,\"Name\":\"Michael\"},{\"Id\":2,\"Name\":\"John\"}]"
我对JSONObjectWithData的调用,不会返回任何错误,但我无法枚举结果,我做错了什么?
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);
}
}
推荐答案
As杰里米指出,你不应该逃避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.
您的实际JSON应如下所示: [{Id:1,Name:Michael} ,{ ID:2 名称: 约翰}]
。没有报价,没有逃脱。消除JSON对象周围的引号后,您的应用程序将不再崩溃,但随后您将获得格式错误的数据(转义)的JSON反序列化错误。
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).
这篇关于NSJSONSerialization解析响应数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!