82

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.

Dexter Cato
  • 1,091
  • 2
  • 10
  • 11

2 Answers2

102

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
StaxMan
  • 113,358
  • 34
  • 211
  • 239
  • 7
    Thank you for this StaxMan. A follow up question which I forgot to put in is how do I insert this node then into an existing node? – Dexter Cato Jul 18 '12 at 10:12
  • Usually you add children by using method of `ObjectNode` or `ArrayNode`; mapper is only used for constructing root nodes. So check out `putObject` or `addObject` method in `ObjectNode`/`ArrayNode` – StaxMan Jul 18 '12 at 19:06
89

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

ObjectNode node = JsonNodeFactory.instance.objectNode();
rand0m86
  • 3,172
  • 4
  • 26
  • 29