我创建了一个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);
}
}发布于 2011-12-28 08:16:54
正如Jeremy所指出的,您不应该转义JSON数据中的引号。而且,您还引用了返回字符串。这使得它是一个JSON字符串,而不是一个对象,所以当你解码它时,你得到的是一个字符串,而不是一个可变的数组,这就是为什么当你试图快速迭代时会得到一个错误的原因……你不能快速迭代一个字符串。
实际的JSON应该类似于:[{"Id":1,"Name":"Michael"},{"Id":2,"Name":"John"}]。没有引号,没有转义。一旦您消除了JSON对象周围的引号,您的应用程序将不再崩溃,但是对于格式错误的数据,您将得到一个JSON反序列化错误(转义)。
发布于 2011-12-28 07:33:40
可能的原因是您使用了错误的基础对象。尝试将NSMutableArray更改为NSDictonary。
来自:的
NSMutableArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&jsonParsingError];To:
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&jsonParsingError];发布于 2013-10-02 06:52:51
使用NSJSONSerialization进行解析很容易,但我还创建了一个小框架,允许将JSON值直接解析为类对象,而不是处理字典。看一看,这可能会有帮助:https://github.com/mobiletoly/icjson
https://stackoverflow.com/questions/8650296
复制相似问题