javajsonjacksonjackson2

Difference between ObjectMapper().createObjectNode vs. JsonNodeFactory.instance.objectNode()?


I saw a post about inserting new nodes to JsonNode and encountered two separate answers, but I can't grasp the difference between the two.

From my little experience, ObjectMapper doesn't allow you to create anything but ObjectNode and ArrayNode while JsonNodeFactory allows you to create a whole bunch of nodes.

Apart from that, what are other differences?

Also, given that ObjectMapper is considered expensive, I was wondering if the latter way is more efficient?


Solution

  • There's no difference between the following approaches:

    ObjectMapper mapper = new ObjectMapper();
    ObjectNode objectNode = mapper.createObjectNode();
    
    ObjectNode objectNode = JsonNodeFactory.instance.objectNode();
    

    Under the hood, Jackson will delegate the createObjectNode() method to JsonNodeFactory.

    For more details on how to use JsonNodeFactory, refer to this answer.