如何动态解析密钥动态变化的json响应

时间:2017-06-15 13:24:35

标签: android json

我的json回复就像

"answers": [{
"data": [
  {
    "currency": "EUR/JPY",
    "rate": "122.593",
    "timestamp": "1497524449141"
  },
  {
    "currency": "EUR/CHF",
    "rate": "1.08779",
    "timestamp": "1497524449234"
  },
  {
    "currency": "USD/CAD",
    "rate": "1.32772",
    "timestamp": "1497524449235"
  },
  {
    "currency": "AUD/USD",
    "rate": "0.75875",
    "timestamp": "1497524449148"
  },
  {
    "currency": "GBP/JPY",
    "rate": "140.248",
    "timestamp": "1497524449230"
  }
],
"metadata": {"count": 60},
"actions": [{
  "type": "table",
  "columns": {
    "currency": "Valuta",
    "rate": "Quota"
  },
  "count": -1
}]
}],

此处操作 Json数组具有json对象列。主要货币和费率名称是动态的,即它可能有其他名称,如游戏和目标或其他任何名称,密钥的数量也可能会发生变化。因此,数据 json数组中的键也会发生变化。数据json数组使用相同的密钥名称。

1 个答案:

答案 0 :(得分:0)

您可以使用Gson libraryparse data object as Array of HashMaps

<强>更新 这是一个小代码示例(我简化了你的JSON):

private void parse() {        
    String json = "[{\"data\":[{\"currency\":\"EUR/JPY\",\"rate\":\"122.593\",\"timestamp\":\"1497524449141\"},{\"currency\":\"EUR/CHF\",\"rate\":\"1.08779\",\"timestamp\":\"1497524449234\"},{\"currency\":\"USD/CAD\",\"rate\":\"1.32772\",\"timestamp\":\"1497524449235\"},{\"currency\":\"AUD/USD\",\"rate\":\"0.75875\",\"timestamp\":\"1497524449148\"},{\"currency\":\"GBP/JPY\",\"rate\":\"140.248\",\"timestamp\":\"1497524449230\"}],\"metadata\":{\"count\":60},\"actions\":[{\"type\":\"table\",\"columns\":{\"currency\":\"Valuta\",\"rate\":\"Quota\"},\"count\":-1}]}]";
    Type type = new TypeToken<List<DataObject>>(){}.getType();
    List<DataObject> list = new Gson().fromJson(json, type);
    for (DataObject object : list) {
        for (HashMap<String, String> map : object.data) {
            Log.e("mapItemStart", "===============");
            for (String item : map.keySet()) {
                Log.e("mapItem", item + " -> " + map.get(item));
            }
            Log.e("mapItemEnd", "===============");
        }
    }
}

public static class DataObject {
    public List<HashMap<String, String>> data;
}