【问题标题】:How to parse JSON response with nested dictionary and dynamic keys in objective-c?如何使用objective-c中的嵌套字典和动态键解析JSON响应?
【发布时间】:2019-01-14 19:54:40
【问题描述】:

如何解析具有嵌套字典和动态键的 JSON 响应?

response dictionary: {
"Meta Data" =     {
    "1. Information" = "Intraday Prices and Volumes for Digital Currency";
    "2. Digital Currency Code" = BTC;
    "3. Digital Currency Name" = Bitcoin;
    "4. Market Code" = USD;
    "5. Market Name" = "United States Dollar";
    "6. Interval" = 5min;
    "7. Last Refreshed" = "2018-08-07 15:45:00";
    "8. Time Zone" = UTC;
};
"Time Series (Digital Currency Intraday)" =     {
    "2018-08-06 01:20:00" =         {
        "1a. price (USD)" = "7074.26229231";
        "1b. price (USD)" = "7074.26229231";
        "2. volume" = "66564.61550730";
        "3. market cap (USD)" = "470895549.48574001";
    };

我试图在我的应用程序中显示最新的比特币价格。 JSON 响应将具有时间间隔作为动态键,例如“2018-08-06 01:20:00”。
我只对“1a.价格(美元)”=“7074.26229231”每个区间的一部分。 考虑到外部键是动态的,我如何获得该值? (每隔 5 分钟会有一个新的键值对用于该时间间隔)

到目前为止我写的代码:

NSString *urlString = @"https://www.alphavantage.co/query?function=DIGITAL_CURRENCY_INTRADAY&symbol=BTC&market=USD&apikey=*******";

NSURL *url = [NSURL URLWithString:urlString];

[[NSURLSession.sharedSession dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    NSError *err;
    NSDictionary *coinDictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&err];
    if (err) {
        NSLog(@"Failed to serialize into JSON: %@", err);
        return;
    }

    NSLog(@"response dictionary: %@", coinDictionary);

}] resume];

完整的 JSON 响应: demo

【问题讨论】:

  • coinDictionary[@"Time Series (Digital Currency Intraday)"] 是一个 NSDictionary。您可以迭代键。我建议创建一个自定义类,其中包含 Date 属性(这是关键)和其余部分。

标签: ios objective-c json parsing


【解决方案1】:

这会打印每个字典的日期键和1a price 的值

NSDictionary *coinDictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&err];
NSDictionary *timeSeries = coinDictionary[@"Time Series (Digital Currency Intraday)"];
for (NSString *key in timeSeries) {
    NSDictionary *rates = timeSeries[key];
    NSString *price1a = rates[@"1a. price (EUR)"];
    NSLog(@"%@ - %@", key, price1a);
}

要仅获取最近的日期,请获取表示日期的字典键,对它们进行排序并获取最后一个。

NSDictionary *coinDictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&err];
NSDictionary *timeSeries = coinDictionary[@"Time Series (Digital Currency Intraday)"];
NSArray *keys = [[timeSeries allKeys] sortedArrayUsingSelector:@selector(compare:)];
NSString *mostRecentDate = keys.lastObject;
NSDictionary *rates = timeSeries[mostRecentDate];
NSString *price1a = rates[@"1a. price (EUR)"];

【讨论】:

  • 拥有所有价格的完美工作解决方案,但由于我只想要最近的价格,如何避免重复完整列表?我总是需要列表中的顶部元素,但由于字典不保留顺序,我怎样才能获得最新的间隔?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-25
相关资源
最近更新 更多