5

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?

Community
  • 1
  • 1
THIS USER NEEDS HELP
  • 3,136
  • 4
  • 30
  • 55

1 Answers1

9

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.

Community
  • 1
  • 1
cassiomolin
  • 124,154
  • 35
  • 280
  • 359
  • So if all I want from `ObjectMapper` is create `ObjectNode`, will it be more efficient if I use `JsonNodeFactory` instead since it won't have to create `ObjectMapper`? – THIS USER NEEDS HELP Sep 12 '16 at 16:36
  • @THISUSERNEEDSHELP If you just need to create `ObjectNode` instances, the `JsonNodeFactory` is enough for you. – cassiomolin Sep 13 '16 at 06:57
  • Just to make sure, even if I am making multiple `ObjectNodes` through `JsonNodeFactory`, it should be cheaper than creating a new `ObjectMapper`? – THIS USER NEEDS HELP Sep 14 '16 at 17:18
  • 1
    @THISUSERNEEDSHELP I haven't done any performance tests, but if you have a look at the `ObjectMapper` default constructor, you'll realize that a lot of objects are being created. For sure it will consume more resources than just using the `JsonNodeFactory`. If you just need to create `ObjectNode` instances and don't need to perform any mappings, use the `JsonNodeFactory`. – cassiomolin Sep 14 '16 at 17:35