我试图解析www.fixer.io JSON以获取货币数据。我在解析JSON并试图将键和值从"rates“字典中分离出来时遇到了麻烦。我需要他们分开,以便我可以把他们放在数组中,以显示货币名称(如:美元,欧元,日本央行)和各自的汇率。
我读到过,我必须使用"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
发布于 2017-02-27 21:46:02
希望这能帮到你,
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);
发布于 2017-02-27 22:04:03
由于rates键包含一个字典,而不是一个数组,所以如果您想要在不同的数组中获取国家名和货币,则不能将国家名和货币作为字典格式,因此需要像下面这样分别获取它们
NSArray *arrKeys = [[json valueForKey:@"rates"] allKeys];
NSArray *arrValues = [[json valueForKey:@"rates"] allValues];
发布于 2017-02-27 21:02:04
根据您的JSON
响应,您必须获得以下所有货币汇率
NSMutableArray *allCurrencyKey = [[json valuesForKey:@"rates"] allKeys];
NSMutableArray *allRates = [json valueForKey:@"rates"];
for(NSString *strCurKey in allCurrencyKey)
{
NSLog (@" %@ rate is %@ ", strCurKey, [allRates valueForKey :strCurKey ]);
}
希望这能帮到你。
https://stackoverflow.com/questions/42500226
复制相似问题