JSONArray to HashMap

2020-02-26 12:43发布

I've a JSONArray and I need to get the hashmap with the values, because I need to populate a stream, like twitter done. What you suggest to do?

标签: android json
2条回答
劳资没心,怎么记你
2楼-- · 2020-02-26 13:05
HashMap<String, String> pairs = new HashMap<String, String>();
for (int i = 0; i < myArray.length(); i++) {
   JSONObject j = myArray.optJSONObject(i);
   Iterator it = j.keys();
   while (it.hasNext()) {
      String n = it.next();
      pairs.put(n, j.getString(n));
   }
}

Something like that.

查看更多
家丑人穷心不美
3楼-- · 2020-02-26 13:20

You can use Iterator for getting JsonArrays. or use this way

eg. json

{
........
........

 "FARE":[   //JSON Array
    {
    "REG_ID":3,
    "PACKAGE_ID":1,
    "MODEL_ID":9,
    "MIN_HOUR":0
    .......
    .......
    .......
    }
      ]
}
HashMap<String, String> mMap= new HashMap<>();
for (int i = 0; i < myArray.length(); i++) {

   JSONObject j = myArray.optJSONObject(i);
    mMap.put("KEY1", j.getString("REG_ID"));
    mMap.put("KEY2", j.getString("PACKAGE_ID"));
    ............
    ............
}

note: For better coding use Iterator

查看更多
登录 后发表回答