[Rest API][JsonPath] [GSON]-> How to Add a node to JSON in JAVA with JSONPath
Recentally, I came across a situation, where I need to update my JSON with new node which can include jsonArray, JsonMap and just updating a node value.
My JSON was like this:
{
"firstName": "John",
"age": 26,
"address": {
"streetAddress": "naist street",
"city": "Nara",
"postalCode": "630-0192"
}
}
And I was expecting it to be like this:
{ "firstName": "John", "lastName": "Mathpal", "address": { "streetAddress": "naist street", "city": "Ranikhet", "postalCode": "630-0192", "landmark": "More Market" }, "age": 26.0, "vehicle": { "name": "honda", "model": "GS", "price": "15.8 L" }, "phoneDetails": [{ "type": "iphone", "number": "123" }, { "type": "android", "number": "456" }] }
So this first change, I was expecting to change the value of city from "Nara" to "Ranikhet".
So to implement it, I used JSONPath DocumentContext which have the set method to set a node value.
So first I read the json file:
String requestBody = readRequestBody(path);
private static String readRequestBody(String requestBodyPath) throws IOException {
File requestBody = new File(requestBodyPath);
return JsonPath.parse(requestBody).jsonString();
}
String valueToBeAddedUpdated = "Ranikhet";
String nodeWhereValueNeedToUpdate = "$.address.city";
requestBody = setJsonDataValue(nodeWhereValueNeedToUpdate, valueToBeAddedUpdated, requestBody);
so to set the value:
private static String setJsonDataValue(String nodeWhereValueNeedToUpdate, Object valueToBeAddedUpdated, String requestBody) {
return JsonPath.parse(requestBody).set(nodeWhereValueNeedToUpdate, valueToBeAddedUpdated).jsonString();
}
It sets the value in the json for city value to :
{
"firstName": "John",
"age": 26,
"address": {
"streetAddress": "naist street",
"city": "Ranikhet",
"postalCode": "630-0192"
}
}
After settign the value, I added a node "lastName": "Mathpal",
requestBody = addJsonNode("$","lastName", "Mathpal",requestBody);
private static String addJsonNode(String jsonpath, String nodeName, String nodeValue, String requestBody) {
DocumentContext documentContext = JsonPath.parse(requestBody);
documentContext.put(JsonPath.compile(jsonpath), nodeName, nodeValue);
String updatedRequestBody = documentContext.jsonString();
return updatedRequestBody;
}
After setting the value, I added a node inside the address: "landmark": "More Market"
requestBody = addJsonNode("$.address","landmark", "More Market",requestBody);
Once this is added, I tried to add a JSONMap vehicle to the existing json.
So to set it, I first prepared a map with vehicle and its details.
String nodeName = "vehicle";
Map<String, Object> finalMap = prepareJsonMapForVehicle(nodeName);
private static Map<String, Object> prepareJsonMapForVehicle(String nodeName) {
Map<String, Object> finalMap = new LinkedHashMap<>();
Map<String, Object> vehicleMap = new LinkedHashMap<>();
vehicleMap.put("name", "honda");
vehicleMap.put("model", "GS");
vehicleMap.put("price", "15.8 L");
finalMap.put(nodeName, vehicleMap);
return finalMap;
}
Once that is done, I used GSON to add that map to the existign requestBody.
requestBody = addJsonMap(requestBody, finalMap);
private static String addJsonMap(String requestBody, Map<String, Object> finalMap) {
HashMap<String, Object> map = new Gson().fromJson(requestBody, HashMap.class);
map.putAll(finalMap);
return new Gson().toJson(map);
}
GSON have 2 methods fromJSON and toJSON which helps to convert java map to json and vice versa.
Once that is done, now added the json array "phoneDetails" field.
So to add it, i first created the jsonArray field as an jsonArray.
String nodeName1 = "phoneDetails";
JsonArray phoneDetails = new JsonArray();
And then added that JSONArray to existing json with the help of JSONPath put method.
String nodeName1 = "phoneDetails";
JsonArray phoneDetails = new JsonArray();
requestBody =addJsonNodeAsArray("$", nodeName1,phoneDetails,requestBody);
in the addJsonNodeAsArray method, I used the JSONPath put method to set the value.
private static String addJsonNodeAsArray(String jsonpath, String nodeName, JsonArray nodeValue, String requestBody) {
DocumentContext documentContext = JsonPath.parse(requestBody);
documentContext.put(JsonPath.compile(jsonpath), nodeName, nodeValue);
String updatedRequestBody = documentContext.jsonString();
return updatedRequestBody;
}
Once the json Array is added, we cans et value for it.
requestBody = addJsonArrayValues("$.phoneDetails", requestBody, "iphone", "123") ;
System.out.println("-------------------------------------------------------------------------------------------");
The only change in this method is, that it takes a map while adding.
private static String addJsonArrayValues(String jsonPath, String requestBody, String arrayNodeName, String arrayNodeValue) {
DocumentContext documentContext= JsonPath.parse(requestBody);
documentContext.add(JsonPath.compile(jsonPath),prepareJsonMapForPhone(arrayNodeName, arrayNodeValue));
String latestIne = documentContext.jsonString();
return latestIne;
}
Once that is done, we can add another json value inside into it too.
requestBody = addJsonArrayValues("$.phoneDetails", requestBody, "android", "456") ;
System.out.println("After adding another value to the jsonArray inside a json:" +requestBody);
This is how I update a json value, added a new json node with value, a json array and a jsonMap into an existing JSON.