Help parsing a nested JSON object

前端 未结 3 1193
别那么骄傲
别那么骄傲 2021-01-06 17:01

I have the following JSON:

{
    \"meta\": {
        \"code\": 200
    }, 
    \"response\": {
        \"deals\": [
            {
                   


        
相关标签:
3条回答
  • 2021-01-06 17:31

    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"]);
    
    0 讨论(0)
  • 2021-01-06 17:39

    [[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.

    0 讨论(0)
  • 2021-01-06 17:45

    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"];
    
    0 讨论(0)
提交回复
热议问题