我从Web服务获得以下JSON:
[
"{
"count":2,
"offers":{
"0":{
"nodeID":"654321",
"publicationDate":"1396272408",
"title":"My first title",
"locations":"New York City"
},
"1":{
"nodeID":"123456",
"publicationDate":"1396272474",
"title":"My second title",
"locations":"San Diego"
}
},
"error":"null",
"result":"success"
}"
]
我需要将此JSON映射到
NSDictionary
。我怎样才能做到这一点?我已经尝试了以下
NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *parsedObject = [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&localError];
但是它只给我一本字典,里面只有一个对象。我需要访问JSON的所有字段,例如
"count"
,"offers"
等。如何实现此目的? 最佳答案
您的JSON输出不是字典,而是数组。
NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSarray *parsedObject = [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&localError];
for(NSDictionary *dict in parsedObject) {
NSNumber *count = [dict objectForKey:@"count"];
}
但是offer节点很奇怪,作为一个数组,这会更好。