-1

所以我正在用 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
}

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

4

2 回答 2

1

只需遍历将“数据”对象放入数组的地图条目:

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);
于 2015-03-10T16:39:11.370 回答
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);
于 2015-03-10T16:45:03.240 回答