Search code examples
javaarraysjsonjson-lib

How to populate JSON from Hashmap data?


I'm working with this data in Java:

HashMap<String, String> currentValues = new HashMap<String, String>();
String currentID;
Timestamp currentTime;
String key;

I need to convert this to JSON, but I can't work out how. Currently I think this is the best approach:

JSONObject dataset = new JSONObject();
dataset.put("date", currentTime);
dataset.put("id", currentID);
dataset.put("key", key);

JSONArray payload = new JSONArray();
payload.add(dataset);

I'm not sure how I'd do this with the Hashmap. I know it's something like this:

JSONObject data = new JSONObject();
Iterator it = currentValues.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry pair = (Map.Entry)it.next();
    
    data.put("type", pair.getKey()) ;
    data.put("value", pair.getValue()) ;
    it.remove(); // avoids a ConcurrentModificationException
}

But the exact syntax and how I'd then add it alongside the other data I can't work out.


Solution

  • You can make JSONObject like below then add it to payload.

    JSONObject dataset = new JSONObject();
    dataset.put("date", currentTime);
    dataset.put("id", currentID);
    dataset.put("key", key);
    
    JSONArray payload = new JSONArray();
    JSONObject data = new JSONObject();
    
    Iterator it = currentValues.entrySet().iterator();
    while (it.hasNext()) {
    Map.Entry pair = (Map.Entry)it.next();
    data.put("type", pair.getKey()) ;
    data.put("value", pair.getValue()) ;
    it.remove(); // avoids a ConcurrentModificationException
    }
    JSONArray mapArray = new JSONArray();
    mapArray.add(data);
    dataset.put("data", mapArray);
    payload.add(dataset);