我有这个JSON。
{
"cnt": 1,
"list": [
{
"object1": [
{
"subobject1": "value1",
"subobject2": "value2",
"subobject3": "value3"
}
],
"object2": {
"subobject1": value1,
"subobject1": value2,
"subobject1": value3
}
}
]
}
我无法从第一个对象获取数据。我收到错误
-[__NSArrayM objectForKeyedSubscript:]: unrecognized selector sent to instance 0x7fa281f82520
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM objectForKeyedSubscript:]: unrecognized selector sent to instance 0x7fa281f82520'
对于另一个对象,我获得了数据,我可以在NSLOG中看到它,但无法理解第一个对象的问题是什么以及应用程序崩溃的原因。
这就是我在数据模型中解析 json 的方式
NSError *deserializationError;
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &deserializationError];
NSArray * responseArr = json[@"list"];
NSMutableArray *result = [[NSMutableArray alloc] init];
if(responseArr && [responseArr isKindOfClass:[NSArray class]]) {
for(NSDictionary *cDictionary in responseArr) {
DAObject *cty = [[DAObject alloc] initWithDictionary:ctyDictionary];
if(cty) {
[result addObject:cty];
}
}
}
然后在对象 .m 文件中
DAServiceObject *object1 = [[DAServiceObject alloc] initWithDictionary:dictionary[@"object1"]];
self.value1 = object1.value1;
self.value2 = object1.value2;
并且应用程序崩溃。
你误解了数据结构:"list"包含一个只有一个项目的数组,即字典。这个字典包含每个键的数组(例如"item1"),同样只有一个项目(再次字典)。
编辑
// ...
if(responseArr && [responseArr isKindOfClass:[NSArray class]]) {
NSDictionary *content = responseArr[0];
for (NSSString *key in [content allKeys]) {
NSDictionary *a = content[key][0];
// ...
}
}
您的 JSON 数据不是数组。这是一本字典。这是一个带有一个键"cnt"和一个键"列表"的字典。键"列表"下的对象是一个数组。