I have a class that looks something like this
public class Converter<T> {
public T convert(String json) throws IOException {
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(json, new TypeReference<T>(){});
}
}
I call the convert method like this
public static void main(String[] args) throws IOException {
Converter<MyJsonObject> converter = new Converter<>();
MyJsonObject json = converter.convert("{\"id\" : 123}");
}
When I run this, I get the error: Exception in thread "main" java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to MyJsonObject
It turns out that convert() method returns a LinkedHashMap instead of MyJsonObject even though I've specified MyJsonObject during Converter construction.
I would like to avoid this solution if possible.
public class Converter {
public <T> T convert(String json, TypeReference ref) throws IOException {
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(json, ref);
}
}
Any help would be appreciated.