【发布时间】: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