javajacksonjsonnode

How to create an empty JsonNode?


I am trying to set an empty node as a value of some other json node. new JsonNode() didn't work as that is protected.

Example:

JsonNode jsonNode = externalSource(); // <--This is the parent json node
((ObjectNode) jsonNode).set("fieldName", new JsonNode()); // <-- I want to replace the existing 
// value of fieldName with an empty one

This will not work currently.

Any particular way we can do this?


Solution

  • ObjectMapper mapper = new ObjectMapper();
    JsonNode node = mapper.createObjectNode();
    

    or you can also do like you said in the comment above,

    JsonNode node = JsonNodeFactory.instance.objectNode();
    

    after that you can map the values,

    JsonNode node = mapper.valueToTree(fromValue);