BleedCode BleedCode - 26 days ago 9
JSON Question

How can i add new line in request message and send back as response

How can i append a line in the json structure.Input JSON is provided by user as html request and each time we need to add date or any other feature in new JSON and return as html response.

if my json file is: {name: abc, age: 12} then my new output json will be {name: abc, age: 12, date:26/09/2017}


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

PrintWriter pw = response.getWriter();

By above code the exisiting json gets deleted only the date displays :(

Answer Source

You can read the entire json in a string and use any JSON parsing library like jettison or jackson. I'll just give an example using jettison:

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.

You can use Jackson's ObjectMapper as well to create a HashMap, or create a POJO to which you can map the object to. The idea is to unmarshall the string to object, add a parameter, and then marshall back to string.