![](/img/trans.png)
[英]How to parse JSON response with nested dictionary and dynamic keys in objective-c?
[英]How to parse a JSON dictionary and put the keys and values in separate arrays - Objective C
我正在尝试解析www.fixer.io JSON以获取货币数据。 我一直在解析JSON并尝试从“比率”字典中分离键和值时遇到麻烦。 我需要将它们分开,以便可以将它们放在数组中以显示货币名称(例如:USD,EUR,JPN)及其各自的汇率。
我读过我必须使用“ allKeys”和“ allValues”来做到这一点,但到目前为止,我还没有运气。 有任何想法吗?
NSURL *fixerURL = [NSURL URLWithString:@"http://api.fixer.io/latest?base=USD"];
NSData *data = [NSData dataWithContentsOfURL:fixerURL];
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSMutableArray *arr = [[NSMutableArray alloc]init];
NSMutableArray *arr2 = [[NSMutableArray alloc]init];
NSArray *names;
NSArray *rates;
for (names in json) {
names = [json allKeys];
for (rates in json) {
rates = [json allValues];
}
[arr addObject:names];
[arr2 addObject:rates];
}
self.currencyList = arr;
self.currencyRates = arr2;
[self updateTableView];
这是JSON ---> http://api.fixer.io/latest?base=USD
希望这个能对您有所帮助,
NSURL *fixerURL = [NSURL URLWithString:@"http://api.fixer.io/latest?base=USD"];
NSData *data1 = [NSData dataWithContentsOfURL:fixerURL];
NSError *error;
NSDictionary *json1 = [NSJSONSerialization JSONObjectWithData:data1 options:kNilOptions error:&error];
NSLog(@"%@",json1);
NSDictionary *json = [[NSDictionary alloc]initWithDictionary:[json1 objectForKey:@"rates"]];
NSMutableArray *arr = [[NSMutableArray alloc] initWithArray:[json allKeys]];
NSMutableArray *arr2 = [[NSMutableArray alloc]initWithArray:[json allValues]];
NSLog(@"%@",arr);
NSLog(@"%@",arr2);
因为Rates键包含一个字典而不是一个数组,所以如果您想以不同的数组来获取国家名称和货币,那么我们就无法将国家名称和货币作为字典格式,因此您需要像下面这样分别获取它们
NSArray *arrKeys = [[json valueForKey:@"rates"] allKeys];
NSArray *arrValues = [[json valueForKey:@"rates"] allValues];
根据您的JSON
响应,您必须按如下所示获得所有货币汇率
NSMutableArray *allCurrencyKey = [[json valuesForKey:@"rates"] allKeys];
NSMutableArray *allRates = [json valueForKey:@"rates"];
for(NSString *strCurKey in allCurrencyKey)
{
NSLog (@" %@ rate is %@ ", strCurKey, [allRates valueForKey :strCurKey ]);
}
希望这对您有帮助。
我不确定您遇到什么错误,但是当我尝试运行此代码时,数据返回为nil。 当然哪个会使应用程序崩溃。
它可能与您用来获取JSON的方法有关。 dataWithContentsOfURL:不应用于基于网络的URL。 dataWithContentsOfURL:
要通过网络获取数据,请查看NSURLSession 。
使用以下代码获取Rates Nad货币名称
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
通过此响应,您可以获得所有费率:
NSMutableDictionary *rates = [json objectForKey:@"rates"];
//Get All Currency Names by `allKeys`.
NSArray *currencyTitles = [rates allKeys];
for(NSString *currencyName in currencyTitles){
//Get Value.
NSString *aStrCurValue = [rates objectForKey:currencyName];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.