1

I looked for a long time for an answer to this and couldn't find anything. Perhaps it is because I don't know how to ask the question as I am new to json. Essentially I am a new ios developer and am trying to learn how to access and use json data. Below is a portion of the json I am using:

{
"status": null,
"data": {
    "1088": {
        "nid": "1088",
        "title": "RE 1 (2000)",
        "articles": [
            {
                "nid": "2488",
                "title": "Copyright Page"
            },
...

etc.

my confusion is that there are two layers with the value title. So when I'm using something like self.dict = [self getDictionaryFromJson]; and have saved the json in a dictionary, then I go to use self.mainTitle = [self.dict objectForKey:@"title"]; and it would presumedly give me back RE 1 (2000). But then I also want to get back the secondary title which is Copyright Page so then i would do self.secondaryTitle = [self.dict objectForKey:@"title"];???

Anyways, my confusion is that I would think it would just again give me back RE 1 (2000) because there is no change to the call and so I don't know how to access the next item with the same key.

Perhaps I am sure the solution is simple I just don't quite understand what I need to do.

2 Answers 2

1

You are neglecting the hierarchy of the data which is mapped into the dict - log it to check.

So, to get the first title (RE 1 (2000)), you would do:

NSString *title = [self.dict valueForKeyPath:@"data.1088.title"];

to drill down through the levels in the JSON (and thus the dictionary). And the same approach applies for deeper nested items (though you can't always use valueForKeyPath: because it won't do what you expect with arrays...).

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! That is exactly what I was wondering how to do. Thanks very much.
1

The JSON you posted contains nested arrays (denoted by square brackets []) and dictionaries (denoted by curly brackets {}). You can convert JSON to an NSDictionary using NSJSONSerialization:

NSData *data = ... // Get JSON Data
self.dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
self.mainTitle = [[[self.dict objectForKey:@"data"] objectForKey:@"1088"] objectForKey:@"title"]
self.secondaryTitle = [[[[[self.dict objectForKey:@"data"] objectForKey:@"1088"] objectForKey:@"articles"] objectAtIndex:0] objectForKey:@"title"]

For more info about JSON, you can read the spec.

1 Comment

Thanks very much! The post by wain answered my question but this helped to clarify the structure of json as well you even took the effort to explain how nsjsonserialization works. Thanks loads!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.