使用 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屋!