tipsywacky
tipsywacky

Reputation: 3464

JSON return value incorrectly parsed in objective C: iOS

{"Overviews":
    [
     {"AAAA": [
               {"Generala": "sometext",
                "Generalb": "sometext",
                "Generalc": "sometext"}
              ],
     "BBBB": [
               {"Generala": "sometext",
                "Generalb": "sometext",
                "Generalc": "sometext"}
              ]
      }
     ]
 }

Hi I used SBJson to parse this json. When I assigned NSArray *json = [jsonObject valueForKey:@"Overviews"];. The hierarchy of data didn't go well. I used one NSDictionary, 2 NSArray and 1 NSString to parse Generala.

My goal is to parse the data "Generala" like this:

NSDictionary *data = [overviews valueForObject:@"AAAA"];
NSString *generals = [data valueForObject:@"Generala"];

What have I done wrong in the json file? Thanks in advance.

Upvotes: 0

Views: 200

Answers (3)

Jaybit
Jaybit

Reputation: 1864

NSArray *dataArray = [overviews objectForKey:@"AAAA"];
NSDictionary *dataDict = [dataArray objectAtIndex:0];
NSString *generals = [dataDict objectForKey:@"Generala"];

This will get you to the correct value, But as you can see I had to "Hard code" the index "0". You would want some logic in there to get to the specific array.

or Change your json to:

{"Overviews":
     {"AAAA":
               {"Generala": "sometext",
                "Generalb": "sometext",
                "Generalc": "sometext"},
     "BBBB":
               {"Generala": "sometext",
                "Generalb": "sometext",
                "Generalc": "sometext"}
      }
}

and use: NSDictionary *dataDict = [overviews objectForKey:@"AAAA"]; NSString *string = [dataDict objectForKey:@"Generala"];

Upvotes: 1

Hot Licks
Hot Licks

Reputation: 47699

Your source is a dictionary of one entry, which entry contains an array of one entry, which entry contains a dictionary of two entries, which entries each contain an array of one entry, which entry contains a dictionary of three entries.

I suspect this is exactly how the JSON parser parsed it.

Upvotes: 1

Jim
Jim

Reputation: 73936

You've got superfluous arrays in there. Overviews is an array with one element in - a dictionary. It should just be the dictionary. The same applies for AAAA and BBBB - they are arrays containing a single dictionary, when they should just be dictionaries.

Basically, just delete all of the square brackets in your JSON.

Upvotes: 2

Related Questions