我有来自网络服务的以下 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 节点很奇怪,作为数组会更好。
关于ios - 在 Objective-C 中将 JSON 映射到 NSDictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22863203/