Googled: com.fasterxml.jackson.databind.ObjectMapper.ObjectMapper() best practice
Found URL: https://stackoverflow.com/a/57671444
private static final ObjectMapper jsonMapper = new ObjectMapper();
Constructing an
ObjectMapper
instance is a relatively expensive operation, so it's recommended to create one object and reuse it. You did it right making itfinal
.
// Suggestion 1: public static <T> T toObject1(final Class<T> type, final String json) throws IOException { return jsonMapper.readValue(json, type); }
You always read JSON to a POJO, so let's be precise and clear, and use
ObjectReader
.
// Suggestion 2: public static <T> T toObject2(final Class<T> type, final String json) throws IOException { return jsonMapper.readerFor(type).readValue(json); } // Suggestion 3: public static <T> T toObject3(final Class<T> type, final String json) throws IOException { return jsonReader.forType(type).readValue(json); }
There is no difference, really. Both methods will construct a new
ObjectReader
object: the former (jsonMapper.readerFor(type)
) will give you a fully-built instance directly, the latter (jsonReader.forType(type)
) will complement the not-yet-usablejsonReader
and returns a ready-to-use object. I would rather go with option 2 because I don't want to keep that field.You shouldn't worry about performance or thread-safety. Even though creating an
ObjectMapper
might be costly (or making a copy out of it), getting and working withObjectReader
s is lightweight and completely thread-safe.From the Java documentation (emphasis mine):
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.I recently had these questions myself and decided on
ObjectMapper#reader(InjectableValues)
as a factory method. It's very handy particularly when you want to customise anObjectReader
slightly or, as it was in my case, to adjust aDeserializationContext
.That's an excellent question, by the way.
No comments:
Post a Comment