73

我创建了一个新的 JsonNode

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

使用此节点,然后如何在其中添加键值对,以便可以使用新值构造此新节点?我在http://www.cowtowncoder.com/blog/archives/2011/08/entry_460.html中读到的关于使用的内容

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

但是查看 Jackson 的 JsonNode (v1.8) 的 API 并没有显示任何这样的方法。

4

2 回答 2

96

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
于 2012-07-16T17:39:33.290 回答
82

我最近发现了更有趣的方法来创建任何ValueNodeContainerNode(Jackson v2.3)。

ObjectNode node = JsonNodeFactory.instance.objectNode();
于 2014-02-26T14:24:46.943 回答