iOS 5谷歌JSON - 如何解析嵌套的对象?
我试图解析一个YouTube播放列表:iOS 5谷歌JSON - 如何解析嵌套的对象?
如果我的JSON的结构类似:
{"apiVersion" ....
"items":[{"id2":"some-id","title":"songtitle",
我完全能够通过解析标题:
// Fill array
NSArray *items = [json objectForKey:@"items"];
// Get item from tableData
NSDictionary *item = [tableData objectAtIndex:[indexPath row]];
// Set text on textLabel
[[cell textLabel] setText:[item objectForKey:@"title"]];
但如果JSON是这样的:
{"apiVersion" ....
"items":[{"id1": .... "video":{"id2":"some-id","title":"songtitle",
我怎样才能达到嵌套目标ct标题?
只是一个简单的事情,但我现在敲我的头在这几个小时。感到沮丧,谢谢你的建议!
[编辑] 这是一个完整的结构:
{
"items":
[
{
"video":
{
"title": "Number One",
"description": "Description one"
},
{
"title": "Number two",
"description": "Description two"
},
{
"title": "Number three",
"description": "Description three"
}
},
{
"video":
{
"title": "Number One",
"description": "Description one"
},
{
"title": "Number two",
"description": "Description two"
},
{
"title": "Number three",
"description": "Description three"
}
}
]
}
的问题是,你的JSON是无效的。所有的titles
应该在数组中对吗?所以他们必须在[]中。您可以使用例如下面的网站“调试”你的JSON:
http://jsonformatter.curiousconcept.com/
此外,在iOS 5中,你可以使用新的内置JSON API。这里是一个很好的教程是: http://www.raywenderlich.com/5492/working-with-json-in-ios-5
尽管如此,这里是你的JSON应该什么样子我想:
{
"items":[
{
"video":[
{
"title":"Number One",
"description":"Description one"
},
{
"title":"Number two",
"description":"Description two"
},
{
"title":"Number three",
"description":"Description three"
}
]
},
{
"video":[
{
"title":"Number One",
"description":"Description one"
},
{
"title":"Number two",
"description":"Description two"
},
{
"title":"Number three",
"description":"Description three"
}
]
}
]
}
与您的项目好运;)
谢谢!我没有发明它:)它的标准jsonc youtube API吐出播放列表(在这里查看真实世界的示例:http://gdata.youtube.com/feeds/api/playlists/6A94E7DAD57DE702?v=2&alt= jsonc)已经开始研究重写这里和那里的东西。 – MartijndeM 2012-04-25 07:19:13
@Martindem OK :),但是仍然从YouTube提供的JSON是有效的json。他们有作为数组的项目,数组中的每个对象都是一个字典。您的示例有不同的并且无效(以json的形式)。无论如何,我希望这个帖子对你有所帮助。再一次,祝你好运;) – 2012-04-25 07:46:00
是的,只是注意到我的简化是无效的*弓头* /直接潜入代码 – MartijndeM 2012-04-25 08:05:00
NSMutableArray *items = [json valueForkey:@"items"];
for(int i =0;i<[items count]; i++)
{
NSMutableArray *arrtitle = [[[items objectAtIndex:i]valueForkey:@"Video"]copy];
for(int j =0;j<[arrtitle count]; j++)
{
NSString *title = [[arrtitle objectAtIndex:j]valueForkey:@"title"];
}
}
也许这会帮助你。
没有,无济于事,工作的第一块JSON,但不是第二块。 Xcode还报告说,标题是一个未使用的变量。 NSLog回声为空。 – MartijndeM 2012-04-24 18:15:57
原因可能是[]。我猜测,这种'的NSMutableArray *项目= [JSON valueForkey:@ “项目”];'这'的NSMutableArray * arrtitle = [[[项目objectAtIndex:我] valueForkey:@ “视频”]复制]'不做同样的事情。由于第二部分不包含** [] **。简单来说,它不是嵌套的JSON。你可能需要一个真正的解析器。只是我2美分。 – Byte 2012-04-24 20:25:19
json层次结构是array> dictionary> dictionary。所以我们必须为小说关键视频计数。所以我们得到更多的三本词典。 – 2012-04-25 04:55:54
试试这个:
NSArray *items = [[json valueForkey:@"items"]valueForkey:"video"];
不,也没有效果。还必须添加@之前的项目和大写的valueForKey。 – MartijndeM 2012-04-24 18:17:44
你能证明你的整个JSON ,它有点混淆这种方式... – 2012-04-24 12:41:48