我对 JSON 解析有一些问题。当我点击 URL 时,我得到如下 JSON 响应:
//JSON 1
{ "data":
{"array":
["3",
{"array":
[
{"id":"1","message":"Hello","sender":"inot"},
{"id":"2","message":"World","sender":"inot"},
{"id":"3","message":"Hi","sender":"marza"}
]
}
]
},
"message":"MSG0001:Success",
"status":"OK"
}
但是如果 data 的结果只是 1,那么 JSON 响应是这样的:
//JSON 2
{ "data":
{"array":
["3",
{"array":
{"id":"3","message":"Hi","sender":"marza"}
}
]
},
"message":"MSG0001:Success",
"status":"OK"
}
我实现此代码以获取 id、消息和发件人值,并在 JSON 1 上正常工作,但在 JSON 2 上出错。我使用 JSON-Framework。问题是如何检测 JSON 响应是对象 ({ }) 还是数组 ([ ]) ?
// Parse the string into JSON
NSDictionary *json = [myString JSONValue];
// Get all object
NSArray *items = [json valueForKeyPath:@"data.array"];
NSArray *array1 = [[items objectAtIndex:1] objectForKey:@"array"];
NSEnumerator *enumerator = [array1 objectEnumerator];
NSDictionary* item;
while (item = (NSDictionary*)[enumerator nextObject]) {
NSLog(@"id = %@",[item objectForKey:@"id"]);
NSLog(@"message = %@",[item objectForKey:@"message"]);
NSLog(@"sender = %@",[item objectForKey:@"sender"]);
}