我有一个类似于json的响应:
{
"status": "success",
"status_code": 200,
"active": {
"owned": [
{
"id": "1",
"name": "Chd Home",
"type": "home",
},
...
],
"shared": [
{
"id": "3",
"name": "Ram's home",
"type": "home",
},
...
]
},
"deactivated": {
"owned": [
{
"id": "2",
"name": "Home",
"type": "home",
}
]
}
我跟随Ray Wanderlich的教程:http://www.raywenderlich.com/5492/working-with-json-in-ios-5,这部分代码专门:
- (void)fetchedData:(NSData *)responseData {
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSArray* latest = [json objectForKey:@"active"]; //2
NSLog(@"items: %@", latest); //3
}
现在,当我想要一个关键对象" active"时,我使用了这个NSArray* latest = [json objectForKey:@"active"];
并获取了最新数组中的数据,但是当我只想要找到<时的对象时/ strong>,我使用此NSArray* latest = [json objectForKey:@"found"];
但最新内容为(null)
我有什么东西在这里失踪吗?如何访问json数组的子对象?就像在这种情况下拥有和共享一样。继续前进我想为有效&gt;创建不同的对象拥有,有效&gt;已共享,已停用&gt;拥有,等等。
感谢阅读。
答案 0 :(得分:2)
你需要的是深入了解json数据字典的层次结构以获取数据。
尝试使用此[[json objectForKey:@"active"] objectForKey:@"owned"]
获取活动和拥有的数据。就像这样,你可以获得停用
答案 1 :(得分:2)
拳头,active
是字典,不是数组。你应该检查错误。
要active
和owned
执行此操作
- (void)fetchedData:(NSData *)responseData {
NSError* error = nil;
NSDictionary *json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
if (error) {
NSLog(@"Error: %@", error);
return;
}
NSDictionary *active = json[@"active"];
NSLog(@"active: %@", active);
NSArray *owned = latest[@"owned"];
NSLog(@"owned: %@", owned);
}
答案 2 :(得分:1)
"active": {
"owned": [
{
"id": "1",
"name": "Chd Home",
"type": "home",
},
...
],
"shared": [
{
"id": "3",
"name": "Ram's home",
"type": "home",
},
...
]
},
活动元素是dictionary
,因为{
已启动,您可以参考http://www.json.org/有关每个符号代表的信息
现在活动元素是一个字典,所以首先你需要获取active
键的字典对象并遍历它以获取该字典的内部对象
NSDictionary* latest = [json objectForKey:@"active"]; // this will give you the dictionary
,最新的元素将是
"owned": [
{
"id": "1",
"name": "Chd Home",
"type": "home",
},
...
],
"shared": [
{
"id": "3",
"name": "Ram's home",
"type": "home",
},
...
]
现在获取密钥owned
的数组作为拥有的[
开头,这就是你想要的那样
NSArray *owned = latest[@"owned"];
这会给你
{
"id": "1",
"name": "Chd Home",
"type": "home",
},
...
这部分