javajsonjacksonobjectmapper

Jackson JsonNode to Typed Collection: Should ObjectReader for TypedReference be Singleton?


When converting a Jackson JsonNode to a Java collection?

See question/answer below: https://stackoverflow.com/a/39237947/15435022

ObjectMapper mapper = new ObjectMapper();  // singleton in the project
...
JsonNode arrayNode = mapper.createArrayNode().add("one").add("two");
ObjectReader reader = mapper.readerFor(new TypeReference<List<Product>>() {});
List<String> list = reader.readValue(arrayNode);

Should ObjectReader for TypeReference, be a singleton within the project, or should it be redeclared everytime the method is called?

I already have ObjectMapper declared as singleton in project.

ObjectReader reader = mapper.readerFor(new TypeReference<List<Product>>() {});

Solution

  • According to the documentation of ObjectReader, instances can be reused:

    Uses "mutant factory" pattern so that instances are immutable (and thus fully thread-safe with no external synchronization); new instances are constructed for different configurations. Instances are initially constructed by ObjectMapper and can be reused, shared, cached; both because of thread-safety and because instances are relatively light-weight.

    Considering the guarantees made in the docs, there is no reason not to use a single instance per type within the project, if you want to.

    P.S. I would not use exactly a singleton, but a cache instead, so that unused instances can be cleared after a time.