0

I have a simple json format with an array within an array, but I can't figure out how to get the inner array. How do I grab the "Commute" tag as an NSArray or a NSDictionary?

Here is my json:

{
    "Language": "EN",
    "Place": [
        {
            "City": "Stockholm",
            "Name": "Slussen",
            "Commute": [
                "Subway",
                "Bus"
            ]
        },
        {
            "City": "Gothenburg",
            "Name": "Central station",
            "Commute": [
                "Train",
                "Bus"
            ]
        }
    ]
}

Here is my code:

NSString *textPath = [[NSBundle mainBundle] pathForResource:@"Places" ofType:@"json"];

NSError *error;
NSString *content = [NSString stringWithContentsOfFile:textPath encoding:NSUTF8StringEncoding error:&error];  //error checking omitted

NSData *jsonData = [content dataUsingEncoding:NSUTF8StringEncoding];

NSDictionary* json = [NSJSONSerialization
                      JSONObjectWithData:jsonData
                      options:kNilOptions
                      error:&error];

NSArray* AllPlaces = [json objectForKey:@"Place"];

for(int n = 0; n < [AllPlaces count]; n++)
{
    PlaceItem* item     = [[PlaceItem alloc]init];
    NSDictionary* place = [AllPlaces objectAtIndex:n];
    item.City           = [place objectForKey:@"City"];
    item.Name           = [place objectForKey:@"Name"];

    NSDictionary* commutes = [json objectForKey:@"Commute"];

    [self.placeArray addObject:(item)];
}
2
  • Commute is an array, not a dictionary. Commented Feb 18, 2013 at 21:12
  • Please find another one-line method to get all you want below Commented Jan 14, 2014 at 11:13

4 Answers 4

2

Your code should be:

NSArray* commutes = [place objectForKey:@"Commute"];

Thwt would give back an array holding "Subway" and "Bus".

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

1 Comment

Most likely a typo but that json dictionary does not contain an element keyed by "Commute".
2
NSArray *commutes = [place objectForKey:@"Commute"];

This will give you an NSArray with "Subway" and "Bus".

Comments

1

I think the problem is the access to json, it should be place instead:

NSArray* commutes = [place objectForKey:@"Commute"];

Comments

0

You can considerably shrink you code using KVC Collection Operators:

NSArray *commutes = [json valueForKeyPath:@"[email protected]"];

If you want all repeated commutes use @unionOfArrays modifier.

Comments

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.