0

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?

1
  • You need to write a (recursive) code that iterates through your JsonNode and finds the relevant key for you and replaces it's value, if found. Commented Jan 30, 2020 at 13:29

1 Answer 1

1

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

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

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.