2017-08-16 59 views
1

我有,我已經使用GSON創建此JSON對象創建一個JSON:如何自定義使用GSON對象在Java中

{ 
"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

您需要創建JsonObject的實例updateJsonObj以更新每個循環使用的密鑰和值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); 
相關問題