我有一个嵌套的Json
:
[
{
"result":"1",
"roleId":4
},
{
"projectInfo":[
{
"result":true
},
{
"Project":[
{
"ProjectId":5378,
"ProjectName":"ASAG",
"CountryId":146,
"ProjectGroupId":743,
"Description":"Axel Spinger AG"
},
{
"ProjectId":5402,
"ProjectName":"BIZ",
"CountryId":146,
"ProjectGroupId":759,
"Description":"Bizerba Win 7 BAU"
},
{
"ProjectId":5404,
"ProjectName":"BOM",
"CountryId":146,
"ProjectGroupId":743,
"Description":"Bombardier Transportation ThinApp Migration"
},
{
"ProjectId":5394,
"ProjectName":"REDBULL",
"CountryId":149,
"ProjectGroupId":762,
"Description":"Red Bull Mac Packaging"
},
{
"ProjectId":5397,
"ProjectName":"VHV",
"CountryId":146,
"ProjectGroupId":743,
"Description":"VHV Win7 Migration"
}
]
}
]
}
]
我需要的是将它分成小块以获得某些特定键的价值,例如:How to parse JSON into Objective C - SBJSON
我的代码是:
SBJsonParser* jParser = [[SBJsonParser alloc] init];
NSDictionary* root = [jParser objectWithString:string];
NSDictionary* projectInfo = [root objectForKey:@"projectInfo"];
NSArray* projectList = [projectInfo objectForKey:@"Project"];
for (NSDictionary* project in projectList)
{
NSString *content = [project objectForKey:@"ProjectId"];
NSLog(@"%@", content);
}
但是在尝试从根节点获取projectInfo
时出现错误。我的代码有什么问题吗?请给我一个例子来分割我的JSON
。任何帮助都会很棒。
答案 0 :(得分:1)
你JSON包含类似嵌套数组。只需将每个内容吐入字典即可获得结果。
工作代码:
SBJsonParser* jParser = [[SBJsonParser alloc] init];
NSArray* root = [jParser objectWithString:string];
NSDictionary* projectDictionary = [root objectAtIndex:1];
NSArray* projectInfo = [projectDictionary objectForKey:@"projectInfo"];
NSDictionary* projectData = [projectInfo objectAtIndex:1];
NSDictionary *projectList = [projectData objectForKey:@"Project"];
NSLog(@"\n\n Result = %@",projectList
);
for (NSDictionary* project in projectList)
{
NSString *content = [project objectForKey:@"ProjectId"];
NSLog(@"\n Project Id =%@", content);
}
答案 1 :(得分:0)
根据您的JSON结构,您的顶级结构是一个数组,而不是字典。
试试这个:
SBJsonParser* jParser = [[SBJsonParser alloc] init];
NSArray* root = [jParser objectWithString:string];
NSDictionary* projectDictionary = [root objectAtIndex:1];
NSArray* projectInfo = [projectDictionary objectForKey:@"projectInfo"];