将JSON对象导入NSArray

时间:2012-03-18 20:57:40

标签: objective-c ios json nsarray

尝试在objective-C中解析此JSON对象并使用这些对象创建NSArray。 第一个值是计数器,并且特定于对象。所有其他值都是唯一的。

{ "myData": [
["1","1","110","dollar","8.0","2.8","0.1","11.6"],
["2","1","110","euro","4.0","3.2","1.5","4.4"],
["3","1","120","rupier","6.0","2.9","1.3","10.8"],
["4","1","120","dinero","4.0","3.3","1.5","4.4"],
["5","2","130","drahmer","8.0","2.9","1.3","11.2"],
] }

试过这段代码:

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

    NSArray *currencyInformation = [json objectForKey:@"myData"];

但是物体不在那里。虽然数组的计数是5。

2 个答案:

答案 0 :(得分:2)

数组中的每个对象都是一个数组本身,所以:

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

NSArray *currencyInformation = [json objectForKey:@"myData"];

for (NSArray *info in currencyInformation) {
    // Then access each "column" with [info objectAtIndex:0,1,2,3,...]
}

答案 1 :(得分:1)

在此数据结构中,您需要按索引访问内容,例如

for (NSArray *currency in currencyInformation) {
    NSLog(@"Currency: %@", [currency objectAtIndex:3]);
}

如果要按密钥访问,则需要更改JSON以使用对象数组而不是数组数组。像这样:

{ 
    "myData": [
        {
            "primaryKey" : 1,
            "currency"   : "dollar",
            <other keys + values>...
        },
    ]
}

在这种情况下,您现在可以执行以下操作:

for (NSDictionary *currency in currencyInformation) {
    NSLog(@"Currency: %@", [currency valueForKey:@"currency"]);
}