Question

I used json-framework to pull a JSON string from and URL and convert the JSON string to NSDictionary object with these two lines of code

SBJsonParser* parser = [SBJsonParser new];
NSDictionary* myDict = [parser objectWithString:resp];

My NSDicitonary has:

(
        {
        condition = no;
        date = "2013-06-21";
        "location_id" = 9;
        name = Chabahil;
        reason = "";
        time = "03:04:22";
    },
        {
        condition = pressure;
        date = "2013-06-21";
        "location_id" = 7;
        name = Maitighar;
        reason = "Peak Hour";
        time = "03:04:13";
    }
)

Now I need to access each element for example I want to get value of "name" of the second element. I couldnot figure out how to do it. Thanks!

Was it helpful?

Solution

The JSON string contains not a dictionary, but an array (of two dictionaries). So you would do

SBJsonParser* parser = [SBJsonParser new];
NSArray* jsonArray = [parser objectWithString:resp];

and access the values for example like

NSString *secondName = [[jsonArray objectAtIndex:1] objectForKey:@"name"];

or, using the modern subscripting syntax:

NSString *secondName = jsonArray[1][@"name"];

(Note that there already is a NSJSONSerialization class in Foundation, so unless you have a specific reason to use SBJsonParser, you could use that as well.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top