2017-09-26 16 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。 这个想法是解开对象的字符串,添加一个参数,然后再回到字符串。 替换最后}用 “日期:”

相关问题