Fabian
Fabian

Reputation: 99

JSONArray to HashMap

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?

Upvotes: 4

Views: 16763

Answers (2)

sivaBE35
sivaBE35

Reputation: 1891

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

Upvotes: 0

Gandalf
Gandalf

Reputation: 9855

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.

Upvotes: 11

Related Questions