0

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.

Example: if my json file is: {name: abc, age: 12} then my new output json will be {name: abc, age: 12, date: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());

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

Srishti
  • 355
  • 1
  • 17
  • you can try convertying json to map, add date to this map, and convert back to json. Look at this https://stackoverflow.com/questions/443499/convert-json-to-map – mlecz Sep 26 '17 at 07:56

2 Answers2

0

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.

Parijat Purohit
  • 921
  • 6
  • 16
0

Just another alternative with regex: Replace last } with ", date:" + date +"}"

Replace Last Occurrence of a character in a string

vladm
  • 43
  • 2
  • 7