我想在地图中存储一些JSON响应的数据。

huangapple go评论84阅读模式
英文:

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&lt;String, Double&gt; map = new HashMap&lt;&gt;();
JSONObject json = new JSONObject(&quot;your json&quot;);
try {
    JSONObject rates = json.getJSONObject(&quot;rates&quot;);
    Iterator&lt;String&gt; cur = rates.keys();
    while(cur.hasNext()){
        map.put(cur.next(), rates.getDouble(cur.next()));
    }
} catch (JSONException e) {
    e.printStackTrace();
}

huangapple
  • 本文由 发表于 2020年4月4日 19:56:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/61027696.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定