Help parsing a nested JSON object

橙三吉。 提交于 2019-11-30 23:09:15

From the JSON you provided, locations is an array (that's what the square brackets mean), so the values that are returned from valueForKey: are contained in NSArray instances (hence the parentheses).

You could use objectAtIndex: before the last call to valueForKey: to obtain just the value you're looking for.

By the way, you can also use valueForKeyPath: to simplify accessing nested values, for example

[deal valueForKeyPath:@"business.name"];

[[deal valueForKey:@"business"] valueForKey:@"locations"] returns an array. Calling -valueForKey: on an NSArray executes valueForKey: for every object in the array and returns an array of the results (see the NSArray documentation for this). So that's what you get, an array of the corresponding values.

You could try changing your code to something like this:

NSDictionary *primaryLocation =  [[[deal valueForKey:@"business"] valueForKey:@"locations"] objectAtIndex:0];
NSLog(@"Address: %@", [primaryLocation valueForKey:@"address"]);
NSLog(@"City: %@", [primaryLocation valueForKey:@"locality"]);
NSLog(@"Phone: %@", [primaryLocation valueForKey:@"phone"]);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!