我有以下JSON数据试图在Objective C中解析 - 我的代码返回较低级别对象值的空值 - userid,FirstName和LastName
完整的JSON是:
{
"members" :
[
{"member" : {"userid":"1","FirstName":"ramesh","LastName":"babu"}},
{"member" : {"userid":"2","FirstName":"ramesh2","LastName":"babu2"}},
{"member" : {"userid":"3","FirstName":"ramesh3","LastName":"babu3"}}
]
}
我的代码是:
- (void)viewDidLoad
{
[super viewDidLoad];
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL: kLatestKivaLoansURL];
[self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSArray* members = [json objectForKey:@"members"]; //2
NSString *text1 = [json description];
jsonSummary.text = text1;
NSEnumerator *e = [members objectEnumerator];
NSArray *keys = [NSArray arrayWithObjects:@"userid", @"FirstName", @"LastName", nil];
NSDictionary * member;
while (member = (NSDictionary *)[e nextObject]) {
// do something with object
// Iterate it
text1 = [member description];
NSLog(@"MEMBER ROW DATA%@", text1);
for (id key in keys) {
text1 = [member description];
NSLog(@"key: %@ value:%@ ", key, [member objectForKey:key]);
}
}
}
任何帮助都将不胜感激!!
答案 0 :(得分:1)
根据示例JSON数据,“members”数组包含每个都有一个键“member”的字典。 “member”键的值包含具有较低级别成员数据的字典。
您的代码假定具有较低级别值的字典是数组元素,但它们不是。
您需要首先获取“成员”键值,然后获取较低级别的值。
更改此行:
NSLog(@"key: %@ value:%@ ", key, [member objectForKey:key]);
为:
NSLog(@"key: %@ value:%@ ", key,
[[member objectForKey:@"member"] objectForKey:key]);
应该这样做,虽然我会稍微更改变量名称,以减少它的混乱。