英文:
I would like to store some data of JSON response in the map
问题
{
"rates": {
"CAD": 1.5299,
"KRW": 1332.82,
"MYR": 4.7006
},
"base": "EUR",
"date": "2020-04-03"
}
我想将这个响应中的部分数据存储在Map中。您能给我一些建议吗?
我想在Map中有这些数据:
"CAD": 1.5299,
"KRW": 1332.82,
"MYR": 4.7006
我需要手动添加吗,还是有更快的方法?
英文:
I have an JSON response from the retrofit which look's like this:
{
"rates": {
"CAD": 1.5299,
"KRW": 1332.82,
"MYR": 4.7006
},
"base": "EUR",
"date": "2020-04-03"
}
And I wondering, How I may store some of that response In the Map? Could you provide me any hint, please?
I would like to have this data in map
"CAD": 1.5299,
"KRW": 1332.82,
"MYR": 4.7006
Do I need to add this manually, or there's some faster way?
答案1
得分: 0
请尝试这样做:
Map<String, Double> map = new HashMap<>();
JSONObject json = new JSONObject("你的 JSON 数据");
try {
JSONObject rates = json.getJSONObject("rates");
Iterator<String> cur = rates.keys();
while(cur.hasNext()){
String key = cur.next();
map.put(key, rates.getDouble(key));
}
} catch (JSONException e) {
e.printStackTrace();
}
英文:
Try this:
Map<String, Double> map = new HashMap<>();
JSONObject json = new JSONObject("your json");
try {
JSONObject rates = json.getJSONObject("rates");
Iterator<String> cur = rates.keys();
while(cur.hasNext()){
map.put(cur.next(), rates.getDouble(cur.next()));
}
} catch (JSONException e) {
e.printStackTrace();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论