6

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?

4
  • 1
    Hello, have you tried this so far? ObjectNode node = mapper.createObjectNode(); Also what do you mean it didn't work? Commented Nov 1, 2022 at 6:43
  • The constructor is not public, it's protected. So a client can not use that directly to instantiate JsonNode. It can only be used by subclasses extending the JsonNode class. Commented Nov 1, 2022 at 6:46
  • To avoid misunderstandings, you have an already existing jsonnode and you want to add to it a new field like "empty": {}? Commented Nov 1, 2022 at 7:54
  • I think I found the solution. Can use object mapper's getNodeFactory and then textNode(...) etc to create JsonNodes Commented Nov 1, 2022 at 8:59

1 Answer 1

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