[英]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.