我在访问JSON中的标题和描述字符串时遇到问题。 我可以到达标签名称和类别名称,但我不知道如何到达项目描述和标题。
这是我的JSON:
{
"tab1":
[
{
"category1Tab1":
[
{
"title":"film1",
"description": "desc1"
},
{
"title": "film2",
"description": "desc2"
}
],
"category2Tab1":
[
{
"title": "tv",
"description": "desc1"
},
{
"title": "tv2",
"description": "desc2"
}
]
}
],
"tab2":
[
{
"category1Tab2":
[
{
"title":"item1",
"description": "desc1"
},
{
"title": "item2",
"description": "desc2"
}
]
}
]
}
这是我的解析代码:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"json"];
NSString *contents = [NSString stringWithContentsOfFile: filePath encoding: NSUTF8StringEncoding error: nil];
SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
NSMutableDictionary *json = [jsonParser objectWithString: contents];
jsonParser = nil;
for (NSString *tab in json)
{
Tab *tabObj = [[Tab alloc] init];
tabObj.title = tab;
NSDictionary *categoryDict = [[json valueForKey: tabObj.title] objectAtIndex: 0];
for (NSString *key in categoryDict)
{
Category *catObj = [[Category alloc] init];
catObj.name = key;
//Code for the items
}
}
如何到达每个标题和描述并将它们推入名为items的Category模型对象数组?
答案 0 :(得分:1)
for (NSString *key in categoryDict)
{
Category *catObj = [[Category alloc] init];
catObj.name = key;
NSArray *items = [categoryDict objectForKey:key];
// you should add error checking to make sure this is actually an NSArray
for (NSDictionary *dict in items) {
NSString *theTitle = [dict objectForKey:@"title"];
NSString *theDescription = [dict objectForKey:@"description"];
// do something with theTitle and theDescription
}
}