2017-09-26 18 views
0

如何在json結構中追加行?輸入JSON由用戶提供爲html請求,每當我們需要添加日期或任何其他功能時新的JSON並返回爲html響應。如何在請求消息中添加新行並作爲回覆發回

例如: 如果我的JSON文件是:{名稱:ABC,年齡:12}然後我的新的輸出JSON將{名稱:ABC,年齡:12,日期:26/09/2017}

CODE:

InputStream inputStream = request.getInputStream(); 
    String text = IOUtils.toString(inputStream, StandardCharsets.UTF_8.name()); 
    JsonObject convertedObject = new Gson().fromJson(text, JsonObject.class); 
    convertedObject.addProperty("Date", "26/09/2017"); 


    PrintWriter pw = response.getWriter(); 
    pw.println(convertedObject.toString()); 

通過上面的代碼等植物學JSON被刪除只有日期顯示:(

+0

你可以嘗試convertying JSON來圖,來添加日期在該地圖上,並轉換回到json。看看這個https://stackoverflow.com/questions/443499/convert-json-to-map – mlecz

回答

0

你可以在一個字符串讀取整個JSON和使用任何JSON解析庫拋放像傑克遜還是我 」。我只是舉一個例子,使用拋棄:

String inp = "{\"key1\": \"value\", \"key2\": {\"key\": \"value\"}}"; 
JSONObject x = new JSONObject(inp); 
System.out.println(x);//the toString method gives the object back 
System.out.println(x.get("key2"));//you can get any key's value by passsing its key 
//setting date here: 
x.putOpt("date", "26/09/2017"); 
System.out.println(x);//you can return the object by doing a toString() of the JSONObject. 

您也可以使用Jackson的ObjectMapper創建HashMap,或者創建一個POJO,您可以將該對象映射到該POJO。 這個想法是解開對象的字符串,添加一個參數,然後再回到字符串。 替換最後}用 「日期:」

相關問題