0

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.

Steven
  • 714
  • 2
  • 8
  • 21
  • 1
    There is no way to know what type needs to substitute `T`. Have clients use the `ObjectMapper` directly or provide that last `convert` method you presented. – Sotirios Delimanolis Aug 04 '16 at 22:01
  • That is because when declaring an anonymous class like: `new TypeReference(){}` the type is retained, and it can be used by the mapper. But with `new TypeReference(){}`, `T` is erased, there is no information there. – Jorn Vernee Aug 04 '16 at 22:03
  • Here: http://stackoverflow.com/questions/34578452/how-to-use-jacksons-typereference-with-generics/34584020 – Sotirios Delimanolis Aug 04 '16 at 22:09
  • Or here: http://stackoverflow.com/questions/6846244/jackson-and-generic-type-reference – Sotirios Delimanolis Aug 04 '16 at 22:09

0 Answers0