Search This Blog

Breaking

Friday, 28 April 2023

April 28, 2023

[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.














April 28, 2023

[JIRA API] -> Set JIRA description field with formatting

 Recentally, while doing my jirafication activity, I came across a situation, when I was trying to create a JIRA Story with sonar issue description, but the JIRA Issue, was not updating the formatted description.

It was coming as a plain text which was not much impressive.

So to  implement it, I did the same steps manually first and then check the request from network console. And below are some of my findings:










1. To make text bold: just put the text between *.

For Example: 

Input Text: This isssue is related to Thread.

Expected Output: *This isssue is related to Thread*

This will make this line bold when you will hit with your API.

API: {{JIRA_URL}}/ rest/api/latest/issue

Method: POST

{

"fields": {

"description": "*This isssue is related to Thread*"

}

}

2. To make text in color: put the color code like this:

"{color:#0747a6}This isssue is related to Thread.{color}"

For Example: 

Input Text: This isssue is related to Thread.

Expected Output: This isssue is related to Thread


3. To put Java code: "{code:java} your java code {code}"

As of now, I have just used these formattings. I will update others, if will use them.



Wednesday, 19 April 2023

April 19, 2023

Sonar Findings - JIRA FIcation


Recentally, I am working on to JIRAfy all our projects Sonar findings. To get start to implement it, I first created a flow diagram. To segregate Sonar issues, I used sonar rule filter. Rule is a filter on the basis of which all soanr issues are categorized. 

For Example: Thread.sleep(1000) should not be a part of test code. 

Every rule is associated with a rule id. So with the help of rule id, I filtered issues. Once i got all the issues, the next step I took, to create JIRA issues for them. 

To jiraficatiom, I first created a epic mentioning the rule and it's description. Inside the epic, I created a story if it does not exist in JIRA. To verify, that a story alredy exist in jira, I used label as a filter, whose value will be rule. Once the story will be created, we will link subtask to it.





This is right now in initial stage, will share details how it will proceede.