【问题标题】:New to JSON API how to access the values in objective-c?JSON API的新手如何访问objective-c中的值?
【发布时间】:2016-11-03 14:39:41
【问题描述】:

下面是我从 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,它将包含其中一个值的字符串?

【问题讨论】:

  • 你有什么问题?您已经了解了一系列属性?是什么阻止你走得更远?
  • 我想我不知道怎么称呼他们?获得 NSArray 后,如何获得 Power Door Locks 的值?我一辈子都想不通。
  • 你已经有一堆代码可以在其他字典和数组中挖掘,所以看起来你应该知道如何挖掘这个attributes数组的字典。迭代数组以获取每个字典。对于每个字典,使用 namevalue 键来获取它们的值。
  • 我不知道为什么现在点击,也许只是有人为我简化了一点。谢谢!

标签: ios objective-c json api


【解决方案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);

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-26
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-22
    相关资源
    最近更新 更多