user3420034
user3420034

Reputation:

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.

Upvotes: -1

Views: 2085

Answers (2)

Archit Maheshwari
Archit Maheshwari

Reputation: 1338

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);

Upvotes: 0

Alex Salauyou
Alex Salauyou

Reputation: 14348

Just iterate over entries of your map putting "data" objects into array:

for (Map.Entry<String, String> e : currentValues) {
    JSONObject j = new JSONObject()
                     .put("type", e.getKey())
                     .put("value", e.getValue());
    payload.add(j);
}

then put array into resulting json:

dataset.put("data", payload);

Upvotes: 0

Related Questions