1

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>>() {});

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.