2

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?

Mooncrater
  • 4,146
  • 4
  • 33
  • 62
  • 1
    Hello, have you tried this so far? `ObjectNode node = mapper.createObjectNode();` Also what do you mean it didn't work? – Jameu Lukasli1 Nov 01 '22 at 06: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. – Mooncrater Nov 01 '22 at 06:46
  • To avoid misunderstandings, you have an already existing jsonnode and you want to add to it a new field like `"empty": {}`? – dariosicily Nov 01 '22 at 07:54
  • I think I found the solution. Can use object mapper's `getNodeFactory` and then `textNode(...)` etc to create JsonNodes – Mooncrater Nov 01 '22 at 08:59

1 Answers1

6
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);
sanurah
  • 976
  • 1
  • 6
  • 16