如何自定义在java

时间:2017-08-16 10:07:53

标签: java json gson

我使用GSON创建了这个JSON对象:

{
"data": {
  "isDeleted": false,
  "period": 201601,
  "columnMap": {
    "1c49eb80-7b53-11e6-bc4b-afbeabb62718": "5000",
    "1c49eb80-7b52-11e6-bc4b-afbeabb62718": "hello",
    "03a534c0-a7f1-11e6-9cde-493bf5c47f4": "AUS",
    "03a534c0-a7fa-11e6-9cde-493bf5c47f4": "123"
    }
  }
}

但我的要求是看起来像

{ 
"data": {
  "isDeleted": false,
  "period": 201601,
    "1c49eb80-7b53-11e6-bc4b-afbeabb62718": "5000",
    "1c49eb80-7b52-11e6-bc4b-afbeabb62718": "hello",
    "03a534c0-a7f1-11e6-9cde-493bf5c47f4": "AUS",
    "03a534c0-a7fa-11e6-9cde-493bf5c47f4": "123"
    }
  }
}

我如何解决这个问题,因为" columnMap"中的所有值都是如此。是动态生成的。

1 个答案:

答案 0 :(得分:1)

您需要创建updateJsonObj的实例JsonObject,以便为每个循环更新columnMap的密钥和值。以下代码片段是解决方案:

String json = "{ \"data\": {\"isDeleted\": false,\"period\": 201601,"
            + "\"columnMap\": {\"1c49eb80-7b53-11e6-bc4b-afbeabb62718\": \"5000\","
            + "\"1c49eb80-7b52-11e6-bc4b-afbeabb62718\": \"hello\","
            + "\"03a534c0-a7f1-11e6-9cde-493bf5c47f4\": \"AUS\", "
            + "\"03a534c0-a7fa-11e6-9cde-493bf5c47f4\": \"123\"}}}";

    Gson gson = new Gson();
    JsonObject root = new JsonParser().parse(json).getAsJsonObject();
    JsonElement dataElement = root.get("data");
    // cobj has value of colummMap of json data
    JsonObject cobj = (JsonObject) root.get("data").getAsJsonObject().get("columnMap");
    JsonObject updateJsonObj = root;
    // remove columnMap node as you wanted !
    updateJsonObj.get("data").getAsJsonObject().remove("columnMap");

    for (Entry<String, JsonElement> e : cobj.entrySet()) {
         //update updateJsonObj root node with key and value of columnMap
         updateJsonObj.get("data").getAsJsonObject().addProperty(e.getKey(), e.getValue().getAsString());
    }

    String updateJson = gson.toJson(updateJsonObj);
    System.out.println(updateJson);