Sangeetharaj
Sangeetharaj

Reputation: 213

How to replace json node in jsonNode or ObjectNode

I have a JSON node-like below. The structure of JsonNode will change dynamically.

Now I want to replace/update the value of a particular key.

Sample JSON One

{
  "company": "xyz",
  "employee": {
    "name": "abc",
    "address": {
      "zipcode": "021566"
    }
  }
}

Sample JSON Two

{
  "name": "abc",
  "address": {
    "zipcode": "021566"
  }
}

I want to replace the zip code value 021566 to 566258. I know key name (zipcode), old and new zip code value but I don't know the path of zip code. I tried multiple ways using com.fasterxml.jackson.databind.JsonNode - put, replace

Is there any way to update in java?

Upvotes: 0

Views: 9311

Answers (1)

djharten
djharten

Reputation: 374

JsonNodes are immutable, but you can find the value you want from a JsonNode, cast the original to an ObjectNode, replace the value, then cast that back to a JsonNode. It's a little odd, I know, but it worked for me.

  public static void findAndReplaceJsonNode throws JsonProcessingException {
    String jsonOne = "{ \"company\" : \"xyz\", \"address\" : { \"zipcode\" : \"021566\", \"state\" : \"FL\" } }";
    String jsonTwo = "{ \"company\" : \"abc\", \"address\" : { \"zipcode\" : \"566258\", \"state\" : \"FL\" } }";

    ObjectMapper mapper = new ObjectMapper();
    JsonNode nodeOne = mapper.readTree(jsonOne);
    JsonNode nodeTwo = mapper.readTree(jsonTwo);

    JsonNode findNode = nodeTwo.get("address");

    ObjectNode objNode = (ObjectNode) nodeOne;
    objNode.replace("address", findNode);
    nodeOne = (JsonNode) objNode;

    System.out.println(nodeOne);
  }

Output:

{"company":"xyz","address":{"zipcode":"566258","state":"FL"}}

Disclaimer: While I do some JSON parsing and processing on a regular basis, I certainly wouldn't say that I'm adept at it or tree traversals with them. There is more than likely a better way to find the value of a child in a JsonNode than by taking the entire child as a node, replacing it's one value and then replacing the node. This should work for you in a pinch, though :)

Upvotes: 1

Related Questions