Reputation: 23
I have following code:
public static <T> T jsonToObject(String json, Class<T> object) {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.readerFor(object).readValue(json);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
What can I do to not return null?
Upvotes: 1
Views: 96
Reputation:
Considering that:
ObjectReader readerFor(
Class<?>
type) - Factory method for constructing ObjectReader that will read or update instances of specified type
<T> T
readValue(String content, TypeReference valueTypeRef) - Method to deserialize JSON content from given JSON content String.
So the method is returning an instance of the generic type Class<T>
, so you can use:
public static <T> T jsonToObject(String json, Class<T> object) {
ObjectMapper mapper = new ObjectMapper();
T instance=null;
try {
instance = mapper.readerFor(object).readValue(json);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
if (instance == null) {
instance = ((Class) ((ParameterizedType) this.getClass().
getGenericSuperclass()).getActualTypeArguments()[0]).newInstance();
}
return instance;
}
Now you will get a new instance if the result is null.
Upvotes: 0
Reputation: 793
Caller will have to deal with this being null/missing anyway so may as well specify that your method throws a JsonProcessingException and do exception handling in the caller. Then the caller can do whatever it needs for the type it needs.
Otherwise you're just handling the same issue twice.
public static <T> T jsonToObject(String json, Class<T> object) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
return mapper.readerFor(object).readValue(json);
}
Upvotes: 3