Tester_Cary
Tester_Cary

Reputation: 39

Adding a new element to an array in the json object java

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

Answers (2)

Shriyansh Gautam
Shriyansh Gautam

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

Subhrajyoti Majumder
Subhrajyoti Majumder

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;
}
  1. Serialize the json -

Response response = objectMapper.readValue(responseJson, Response.class);

  1. Add the new incoming node object to response -

response.getNodes().add(New Node("{new node Value}"));

  1. Deserialize before post -

objectMapper.writeValueAsString(response);

Upvotes: 0

Related Questions