[英]complex JSON parsing using Objective-C
{
"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
}
}
}
This was the json output 这是json输出
How can I parse inside the items of 3 and 4, say getting the id, energy and name 我如何解析3和4的内容,例如获取ID,能量和名称
Thanks! 谢谢!
If the order inside Flight1 doesn't matter, the following should work: 如果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"];
…
}
Otherwise, if you want the keys sorted according to their numeric value: 否则,如果要根据键的数值对键进行排序:
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"];
…
}
Assuming that you are using the json framework you could access it like this: 假设您正在使用json框架 ,则可以这样访问它:
NSDictionary *jsonDict = [jsonString JSONValue];
NSString *id = [[[jsonDict objectForKey:@"Flight1"] objectForKey:@"3"] objectForKey:@"id"];
This assumes alot, so make use of try except blocks or iterate through the different levels. 这假设很多,因此请尝试使用try除了块,或遍历不同级别。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.