0

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.