Search code examples
objective-cxcodensdictionary

Reading NSDictionary of JSON data


I have JSON data:

{"data":[
     {"userID":"1", "username":"name1"},
     {"userID":"2", "username":"name2"},
     {"userID":"3", "username":"name3"}
]}

returned into an NSDictionary.

NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:jsonReturnData options:kNilOptions error:&err];

The jsonObject looks like this:

enter image description here

How do I then read the values in the NSDictionary? I have:

NSDictionary *dictItem1 = (NSDictionary *)jsonObject;

which reads the data item but how do get the values?


Solution

  • Finally got it reading the data into an NSArray:

    NSArray *JsonData = [NSJSONSerialization JSONObjectWithData:jsonReturnData options:NSJSONReadingAllowFragments error:&err];
    NSArray *array = [JsonData objectAtIndex:0];
    NSDictionary *dictItem = (NSDictionary *)array;
    NSArray *arrayItems = [dictItem objectForKey:@"data"];
    

    The arrayItems then held each of the records.

    As pointed out it be further simplified with:

    NSArray *JsonData = [NSJSONSerialization JSONObjectWithData:jsonReturnData options:NSJSONReadingAllowFragments error:&err];
    NSDictionary *dictItem = (NSDictionary *)[JsonData objectAtIndex:0];;
    NSArray *arrayItems = [dictItem objectForKey:@"data"];