如何解析具有嵌套字典和动态键的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。价格(USD)” =每个间隔的“ 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
答案 0 :(得分:0)
这会打印日期键和每个字典的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)"];