NSJSONSerialization分析响应数据

我创build了一个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); } } 

正如Jeremy所指出的那样,您不应该在JSON数据中避开引号。 而且,你已经引用了返回string。 这使得它是一个JSONstring,而不是一个对象,所以当你解码它时,你有一个string,而不是一个可变的数组,这就是为什么当你尝试快速迭代时你得到一个错误…你无法快速迭代一个string。

您的实际JSON应该如下所示: [{"Id":1,"Name":"Michael"},{"Id":2,"Name":"John"}] 没有引号,没有逃脱。 一旦消除了JSON对象的引号,你的应用程序就不会崩溃,但是你会得到一个JSON反序列化错误的数据格式错误(转义)。

可能的原因是您正在使用错误的基础对象。 尝试将NSMutableArray更改为NSDictonary。

从:

 NSMutableArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&jsonParsingError]; 

至:

 NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&jsonParsingError]; 

用NSJSONSerialization进行parsing很简单,但我也创build了一个小框架,它允许将JSON值直接parsing到类对象中,而不是处理字典。 看看,这可能是有帮助的: https : //github.com/mobiletoly/icjson