Reputation: 39
I am writing automation script to validate json responses of REST APIs and i am using faster xml to serialize and convert java object to json format. I have a user case where I have to get the json response and add a new array element to an existing array and post it back. The json response after GET looks like this :
{
"name":"test",
"id":"1234",
"nodes":[
{
"nodeId":"node1"
},
{
"nodeId":"node2"
}
]
}
To this json response, I need to add a third entry for nodes array
{ "nodeId": "node3" }
and then post this.
Can someone please help me understand how to add a new array element to an existing array?
Upvotes: 0
Views: 3880
Reputation: 1082
You can try:
//Your JSON response will be in this format
String response = "{ \"name\":\"test\", \"id\":\"1234\", \"nodes\":[ { \"nodeId\":\"node1\" }, { \"nodeId\":\"node2\" } ] }";
try {
JSONObject jsonResponse = new JSONObject(response);
JSONArray nodesArray = jsonResponse.getJSONArray("nodes");
JSONObject newEntry = new JSONObject();
newEntry.put("nodeId","node3");
nodesArray.put(newEntry);
jsonResponse.put("nodes",nodesArray);
} catch (JSONException e) {
e.printStackTrace();
}
Now you can post your jsonResponse.toString()
as required.
Upvotes: 1
Reputation: 41200
I would rather go for cleaner approach, create Object with below structure -
public class Response{
private String name;
private int id;
private List<Node> nodes;
<Getter & Setter>
}
public class Node{
private String nodeId;
}
Response response = objectMapper.readValue(responseJson, Response.class);
response
-response.getNodes().add(New Node("{new node Value}"));
objectMapper.writeValueAsString(response);
Upvotes: 0