How to append a String to JSON String in java?
java, json, string
Solution
Use a JSON Parser/Generator to parse your given JSON to a tree structure and then add your JSON field.
With Gson, that would look something like this
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(ss, JsonObject.class); // parse
jsonObject.addProperty("version", "v3"); // modify
System.out.println(jsonObject); // generate
prints
{"description":"Some Text","machinename":"machineA","ipaddress":"192.128.0.0","version":"v3"}
Will Zookeeper always return valid JSON or their custom format? Be aware of that.
Problem
I am getting the data from the Zookeeper node like this ``` byte[] bytes = client.getData().forPath("/my/example/node1"); String ss = new String(bytes); ``` Here `ss` will have data like this which is a simple JSON String consisting of key value pair - ``` {"description":"Some Text", "machinename":"machineA", "ipaddress":"192.128.0.0"} ``` Now I want to append one more key value pair at the end to the above JSON String. This is the below key value pair I want to append - ``` "version":"v3" ``` So the final JSON String will look like this - ``` {"description":"Some Text", "machinename":"machineA", "ipaddress":"192.128.0.0", "version":"v3"} ``` What's the best and efficient way to do this?