Best way to use Jackson JsonNodeFactory

Drew H picture Drew H · Jun 10, 2011 · Viewed 52.6k times · Source

I'm using Jackson to build a custom JSON object. Is the correct way of going about this?

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);

Answer

StaxMan picture StaxMan · Jun 12, 2011

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");

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.