使用Jackson JsonNodeFactory的最佳方式 [英] Best way to use Jackson JsonNodeFactory
问题描述
我正在使用Jackson构建自定义JSON对象。这是正确的方法吗?
I'm using Jackson to build a custom JSON object. Is the correct way of going about this?
它似乎运作良好(并且输出正确)但我可能会错过我使用JsonNodeFactory的方式。对象是否意味着像我在这里所做的那样传递?
It seems to work well (and the output is correct) but I may be missing the way I use JsonNodeFactory. Is the object meant to be passed around like I have done here?
JsonNodeFactory factory = JsonNodeFactory.instance;
ObjectNode dataTable = new ObjectNode(factory);
ArrayNode aaData = new ArrayNode(factory);
for (PkgLoad pkgLoad : pkgLoadList) {
ObjectNode row = new ObjectNode(factory);
row.put("ounces", pkgLoad.ounces);
row.put("revolutions", pkgLoad.revolutions);
aaData.add(row);
}
dataTable.put("aaData", aaData);
推荐答案
这是有效的,虽然意图是它的工厂创建实例。但最常见的是你只需使用ObjectMapper访问所有内容,例如:
This works, although intention is that it's factory that creates instances. But most commonly you just access all of it using ObjectMapper, like:
ObjectMapper mapper = new ObjectMapper();
ObjectNode dataTable = mapper.createObjectNode();
ArrayNode aa = dataTable.putArray("aaData");
单独的JsonNodeFactory的主要原因是允许您创建自定义节点类型(通常是子类标准实例);然后配置ObjectMapper以使用不同的工厂。
为方便起见,ArrayNode和ObjectNode确实引用了一个工厂实例,它与putArray以及需要创建新节点的其他方法一起使用。
The main reason for separate JsonNodeFactory is to allow you to create custom node types (usually sub-classes of standard instances); and then configure ObjectMapper to use different factory. For convenience, ArrayNode and ObjectNode do have reference to a factory instance, which is used with "putArray" and other methods that need to create new nodes.
这篇关于使用Jackson JsonNodeFactory的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!