Summary
I want to find the best practice for using ObjectMapper
and/or ObjectReader
in terms of thread-safety and performance in the context of the use-case described below.
Background
I have a helper class (Json.java) where the method toObject()
uses ObjectMapper
to translate from a json
string to an object of a given (json-mappable) class.
Problem / question
I have read that ObjectReader
is often recommended for being fully thread-safe, but I mostly see it being in a non-generic context where the class to read for is predefined. In this context, what do you believe to be the best practice in terms of thread-safety and performance? In the code I have three suggestions that I could think of as a starting point.
I have tried to look at through the source code and docs for jackson-databind
, but my theoretical Java skills are not good enough to derive an answer from them. I have also looked at similar questions on SO and elsewhere, but haven't found any that match my case closely enough.
import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
public abstract class Json {
private static final ObjectMapper jsonMapper = new ObjectMapper();
// NOTE: jsonReader is only relevant for Suggestion 3.
private static final ObjectReader jsonReader = jsonMapper.reader();
// Suggestion 1:
public static <T> T toObject1(final Class<T> type, final String json) throws IOException {
return jsonMapper.readValue(json, type);
}
// 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);
}
// Remainder of class omitted for brevity.
}