JSON API 新手如何访问 Objective-C 中的值?

问题描述 投票:0回答:1

下面是我从 Edmunds.com 访问 JSON API 的代码,这非常适合访问我只是在访问键值对时遇到问题的信息。

NSURL *equipmentURL = [NSURL URLWithString: [NSString stringWithFormat:@"https://api.edmunds.com/api/vehicle/v2/styles/%@/equipment?fmt=json&api_key=%@", self.carID, apiKey]];

    NSData *jsonData = [NSData dataWithContentsOfURL:equipmentURL];

    NSError *error = nil;

    NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];

    self.engineArray = [NSMutableArray array];

    NSArray *equipmentArray = [dataDictionary objectForKey:@"equipment"];

    for (NSDictionary *carInfoDictionary in equipmentArray) {

        NSArray *attributes = [carInfoDictionary objectForKey:@"attributes"];
        NSLog(@"%@", attributes);

    }

在上面代码的 NSLog 中显示:

2016-11-03 10:21:26.029 CarWise[25766:1896339] (
        {
        name = "Engine Immobilizer";
        value = "engine immobilizer";
    },
        {
        name = "Power Door Locks";
        value = "hands-free entry";
    },
        {
        name = "Anti Theft Alarm System";
        value = "remote anti-theft alarm system";
    }
)

我的主要问题是如何访问每个数组的名称和值?假设我想创建一个 UILabel,它将包含其中一个值的字符串?

ios json objective-c
1个回答
1
投票

这可能会有帮助

//按照帖子的数组

NSArray *attributes = (NSArray *)[carInfoDictionary objectForKey:@"attributes"];

// 循环迭代对象数组(字典)

for (int i = 0; i < attributes.count; i++) {
    NSDictionary * dataObject = [NSDictionary dictionaryWithDictionary:(NSDictionary *)attributes[i]];

    // This is the value for key "Name"
    NSString *nameData = [NSString stringWithString:[dataObject valueForKey:@"name"]];

    NSLog(@"Value of key : (name) : %@", nameData);

}
© www.soinside.com 2019 - 2024. All rights reserved.