-1

So I'm working with this data in Java:

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

Which I need to convert to this JSON:

{
    "date" : "23098272362",
    "id"   : "123",
    "key"  : "secretkey",
    "data" : [{
             "type"  : "x",
             "value" : "y"
         },{
             "type"  : "a",
             "value" : "b"
         }
     ]
}

But I can't quite work out how.

Currently I'm thinking 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);

But I'm unsure 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. Any ideas?

user3420034
  • 1,275
  • 2
  • 20
  • 43
  • possible duplicate of [Putting HashMap in jsonobject](http://stackoverflow.com/questions/17444396/putting-hashmapstring-object-in-jsonobject) – Prerak Sola Mar 10 '15 at 16:36
  • @PrerakSola I already know how to add the Hashmap to a JSONObject, my issue is how you then add that within 'data'. That solution is actually in my question? So strange that you linked to it. :p – user3420034 Mar 10 '15 at 16:38

2 Answers2

1

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);
Alex Salauyou
  • 13,786
  • 4
  • 41
  • 67
1

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);
Archit Maheshwari
  • 1,287
  • 1
  • 9
  • 13