mm24
mm24

Reputation: 9596

JSON: Understanding format in Objective-C

Given the following JSON payload I would like to extract "023" from keyB->key2:

JSON Payload:

{
    "keyA" : {"lon": 139, "lat" : 35},
    "keyB" : [ {"key1" : "value", "key2" : "023"} ]
}

This is the code I apply:

    NSDictionary * subResults = jsonResult[@"keyB"];
    NSLog(@"VALUE: %@", [subResults valueForKey:@"key2"])

However the value is printed as following:

VALUE: (
    023
)

I want to get rid of the brackets "(". Am I approaching the extraction in the wrong way?

Upvotes: 0

Views: 59

Answers (2)

Richard Stelling
Richard Stelling

Reputation: 25665

The brackets show the value you want is inside an array.

NSData strAsData = …;
NSDictionary *jsonResult = [NSJSONSerialization JSONObjectWithData:strAsData options:0 error:nil];
NSArray *subResults = jsonResult[@"keyB"];
NSDictionary *subSubResults = subResults[0];

NSLog(@"VALUE: %@", subSubResults[@"key2"]);

Because the array only has one item you can use a call to -lastObject or -firstObject

Upvotes: 2

Florian Burel
Florian Burel

Reputation: 3456

First, your json as given is not valid son :( you have a quote to many. If we escape it like this:

{"keyA":{"lon":139,"lat":35},"keyB":[{"key1":"value\" clouds","key2":"023"}]}

Then, it's ok. Now, what you have here is an son object, containing 2 keys (A and B). And KeyB is associated with a json Array meaning :

 jsonResult[@"keyB"];

Does not return a NSDictionnary but a NSArray, containing 1 NSDictionary. Now if you try to get the value "023", you should use

NSString str = jsonResult[@"keyB"][0][@"key2"]; // return "023"

and maybe

int twentyThree = str.intValue;

Upvotes: 3

Related Questions