0

我有一个简单的 json 格式,数组中有一个数组,但我不知道如何获取内部数组。如何将“通勤”标签作为 anNSArray或 a获取NSDictionary

这是我的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

4 回答 4

2

您的代码应该是:

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

Thwt 将返回一个数组,其中包含"Subway"and "Bus"

于 2013-02-18T19:29:57.077 回答
2

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

NSArray* commutes = [place objectForKey:@"Commute"];
于 2013-02-18T19:33:13.100 回答
2
NSArray *commutes = [place objectForKey:@"Commute"];

这将为您NSArray提供“地铁”和“公共汽车”。

于 2013-02-18T19:33:25.770 回答
0

您可以使用 KVC 集合运算符显着缩减代码:

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

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

于 2014-01-14T11:10:08.557 回答