{
"Flight1":{
"3":{
"id":"10",
"name":"JumboJet1B",
"level":"1",
"category":"1",
"energy":"10",
"bonus":"10",
"completed":0
},
"4":{
"id":"10",
"name":"JumboJet1B",
"level":"1",
"category":"1",
"energy":"10",
"bonus":"10",
"completed":0
}
}
}
这是json输出
如何解析3和4中的项目,比如获取id,energy和name
谢谢!
答案 0 :(得分:1)
如果Flight1中的订单无关紧要,则以下内容应该有效:
NSDictionary *flights = … // result from a JSON parser
NSDictionary *flight1 = [flights objectForKey:@"Flight1"];
for (NSString *key in [flight1 allKeys]) {
NSDictionary *flight1Entry = [flight1 objectForKey:key];
NSString *entryId = [flight1Entry objectForKey:@"id"];
NSString *entryName = [flight1Entry objectForKey:@"name"];
NSString *entryEnergy = [flight1Entry objectForKey:@"energy"];
…
}
否则,如果您希望按照其数值排序键:
NSDictionary *flights = … // result from a JSON parser
NSDictionary *flight1 = [flights objectForKey:@"Flight1"];
NSArray *flight1Keys = [[flight1 allKeys] sortedArrayUsingComparator:^(id o1, id o2) {
NSInteger i1 = [o1 integerValue];
NSInteger i2 = [o2 integerValue];
NSComparisonResult result;
if (i1 > i2) result = NSOrderedDescending;
else if (i1 < i2) result = NSOrderedAscending;
else result = NSOrderedSame;
return result;
}];
for (NSString *key in flight1Keys) {
NSDictionary *flight1Entry = [flight1 objectForKey:key];
NSString *entryId = [flight1Entry objectForKey:@"id"];
NSString *entryName = [flight1Entry objectForKey:@"name"];
NSString *entryEnergy = [flight1Entry objectForKey:@"energy"];
…
}
答案 1 :(得分:0)
假设您使用的是json framework,您可以像这样访问它:
NSDictionary *jsonDict = [jsonString JSONValue];
NSString *id = [[[jsonDict objectForKey:@"Flight1"] objectForKey:@"3"] objectForKey:@"id"];
这假定很多,所以使用try除了块或迭代不同的级别。