Pregunta

I have a JSON response of the below format & I parse it into a NSMutableDictionary , which again I am trying to filter into separate dictionaries.For example, from the below response I want to make a membersDictionary out of the whole JSON response but can't find a way to do it.

[
    {
        "members": [
            {
                "lat": "45.747711",
                "lng": "4.824100"
            },
            {
                "lat": "47.747711",
                "lng": "3.824100"
            }
        ],
        "professionnels": [
            {
                "lat": "45.747711",
                "lng": "4.824100"
            },
            {
                "lat": "47.747711",
                "lng": "3.824100"
            }
        ]
    }
] 

This is how I make a separate dictionary out of the whole response.

NSMutableArray *latArray = [[NSMutableArray alloc] init];
NSMutableArray *lngArray = [[NSMutableArray alloc] init];

for (NSDictionary *obj in self.jsonDictionary) //this is NSMutableDictionary which contains whole response.
{
    _membersDict = [obj objectForKey:@"members"];

    for (NSDictionary *obj in _membersDict)
    {
        NSString *latitudeString = [obj objectForKey:@"lat"];
        NSString *longitudeString = [obj objectForKey:@"lng"];

        [latArray addObject:latitudeString];
        [lngArray addObject:longitudeString];
    }
}
NSLog(@"members dict  fetched %@", _membersDict);  // SHOWS NULL 
NSLog(@"latitude array - %@", latArray);           // shows values
NSLog(@"longitude array - %@", lngArray);          // shows values
¿Fue útil?

Solución

Your JSON have array of dictionaries, so first cast it to array and loop over the array. In each iteration you will have a dictionary and then you can access them. [] shows array.

 for (NSDictionary *dic in jsonArray){
    //Now your dic store key value, and value is again in array
    NSArray *memberArray = [dic objectForKey:@"member"];
    //memberArray contain dictionarys
    for (NSDictionary *memDic in memberArray){
    NSString *lat = memDic objectForKey:@"lat"];
    //and same for other value
    }
    //Now do the same for professional

    }

Otros consejos

The most simplest way is to use KVC Collection Operators:

NSArray *latArray = [self.jsonDictionary valueForKeyPath:@"@unionOfArrays.members.lat"];
NSArray *lngArray = [self.jsonDictionary valueForKeyPath:@"@unionOfArrays.members.lng"];
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top