how to create insert new nodes in JsonNode?

JsonJackson

Json Problem Overview


I have a new JsonNode that I created

JsonNode jNode = new ObjectCodec().createObjectNode();

with this node, how do I then add key value pairs within so that I can construct this new node with the new values? What I read in http://www.cowtowncoder.com/blog/archives/2011/08/entry_460.html mentioned about using

jNode.with("newNode").put("key1","value1");

But looking at the APIs for Jackson's JsonNode (v1.8) does not show any method as such.

Json Solutions


Solution 1 - Json

These methods are in ObjectNode: the division is such that most read operations are included in JsonNode, but mutations in ObjectNode and ArrayNode.

Note that you can just change first line to be:

ObjectNode jNode = mapper.createObjectNode();
// version ObjectMapper has should return ObjectNode type

or

ObjectNode jNode = (ObjectNode) objectCodec.createObjectNode();
// ObjectCodec is in core part, must be of type JsonNode so need cast

Solution 2 - Json

I've recently found even more interesting way to create any ValueNode or ContainerNode (Jackson v2.3).

ObjectNode node = JsonNodeFactory.instance.objectNode();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDexter CatoView Question on Stackoverflow
Solution 1 - JsonStaxManView Answer on Stackoverflow
Solution 2 - Jsonrand0m86View Answer on Stackoverflow