简体   繁体   中英

How to get particular object values and key values from JSON response?

I need to get Particular Object values ( A, B, C, D) and related key values (@"name" ). Here below I have posted my sample code and response. Please help me.

NSString *combined = URL;
NSURL *url = [[NSURL alloc] initWithString:combined];
NSData *responseData=[NSData dataWithContentsOfURL:url];
NSError *error;
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSArray *responsData = [jsonDictionary objectForKey:@"response"];

// GET A,B,C Object values
NSDictionary *d1 = responsData.firstObject;
NSEnumerator *enum1 = d1.keyEnumerator;
NSArray *firstObject = [enum1 allObjects];

My JSON Response :

response : [  {

                    A   =  [   {  
                             name : tango 
                               }
                           {
                            name : ping
                           }
                         ]

                    B  =  [   {  
                             name : tango 
                               }
                           {
                            name : ping
                           }
                        ]
                 } ] 

Simply

for(NSDictionary *dict in firstObject){
    NSLog(@"%@",[dict objectForKey:@"name"]);
}

You can achieve the list of all names using this:

NSMutableArray *names = [[NSMutableArray alloc] init];

    for (NSDictionary *dict in responsData) {

        [dict enumerateKeysAndObjectsUsingBlock: ^(id key, id obj, BOOL *stop) {
            NSArray *valueArray = (NSArray *)obj;

            for (NSDictionary * namesDict in valueArray) {
                [names addObject:namesDict[@"name"]];
            }
        }];
    }

Output:

NSLog(@"Names %@",names);

tango, ping, tango, ping.

Hope that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM