How do I parse JSON response that has nested dictionary and dynamic keys ?
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";
};
I am trying to show the latest BitCoin price in my app. JSON response will have time interval as dynamic keys, such as “2018-08-06 01:20:00”.
I am only interested in “1a. price (USD)” = “7074.26229231” part of each interval. How can I get that value considering the fact that outer keys will be dynamic? (every 5 minutes there will be a new key value pair for that interval)
Code I have written so far:
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];
full JSON response: demo
This prints the date key and the value for 1a price
of each dictionary
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);
}
To get only the most recent date get the dictionary keys which represent the dates, sort them and get the last one.
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)"];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.