iOS JSon解析,数组中的数组

时间:2013-02-18 19:22:16

标签: ios json

我有一个简单的json格式,在数组中有一个数组,但我无法弄清楚如何获取内部数组。如何将“Commute”标记作为NSArrayNSDictionary抓取?

这是我的json:

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

这是我的代码:

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)];
}

4 个答案:

答案 0 :(得分:2)

您的代码应为:

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

这会返回一个包含"Subway""Bus"的数组。

答案 1 :(得分:2)

我认为问题在于访问json,而应该是place

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

答案 2 :(得分:2)

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

这将为您提供NSArray“Subway”和“Bus”。

答案 3 :(得分:0)

使用KVC Collection Operators可以大大缩小代码:

NSArray *commutes = [json valueForKeyPath:@"Place.@distinctUnionOfArrays.Commute"];

如果您想要所有重复的通勤使用@unionOfArrays修饰符。