如何从Hashmap数据填充JSON?

时间:2015-03-10 16:29:41

标签: java arrays json json-lib

所以我在Java中使用这些数据:

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

我需要将其转换为此JSON:

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

但我无法弄清楚如何。

目前我认为这是最好的方法:

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

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

但我不确定如何使用Hashmap执行此操作。我知道它是这样的:

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
}

但确切的语法以及我如何将其与其他数据一起添加我无法解决。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

只需迭代地图的条目即可放置&#34;数据&#34;对象到数组:

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

然后将数组放入生成的json:

dataset.put("data", payload);

答案 1 :(得分:1)

您可以像下面那样制作JSONObject,然后将其添加到有效载荷中。

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