Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create insert new nodes in JsonNode?

Tags:

json

jackson

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.

like image 469
Dexter Cato Avatar asked Jul 16 '12 11:07

Dexter Cato


People also ask

What is the difference between JsonNode and ObjectNode?

JsonNode represents any valid Json structure whereas ObjectNode and ArrayNode are particular implementations for objects (aka maps) and arrays, respectively.

What is difference between JsonNode and Jsonobject?

ObjectNode is a concrete implementation of JsonNode that maps a JSON object, and a JSON object is defined as following: An object is an unordered set of name/value pairs.


2 Answers

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
like image 123
StaxMan Avatar answered Oct 08 '22 09:10

StaxMan


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

ObjectNode node = JsonNodeFactory.instance.objectNode();
like image 38
rand0m86 Avatar answered Oct 08 '22 09:10

rand0m86