Jackson-databind: TypeReference doesn't work with generic type parameter

Created on 8 Jan 2017  路  2Comments  路  Source: FasterXML/jackson-databind

I have a method that convert json string into a Map with generic value type:

public <T> Map<String, T> convert(String str) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    return mapper.readValue(str, new TypeReference<Map<String, T>>() {});
}

The example usage:

Map<String, Foo> map = obj.convert(jsonString);

When run, I got error:

Exception in thread "main" java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.example.Foo

Is there a solution for this?

Most helpful comment

@s101d1 Such usage can not be supported, unfortunately, since type variable T is only known to compiler and there is no real parameter passed during runtime. So T can only be known as java.lang.Object; anything caller uses will only result in a cast.

The solution is to pass actual Class<T> value along: this must be passed to know the type.

All 2 comments

@s101d1 Such usage can not be supported, unfortunately, since type variable T is only known to compiler and there is no real parameter passed during runtime. So T can only be known as java.lang.Object; anything caller uses will only result in a cast.

The solution is to pass actual Class<T> value along: this must be passed to know the type.

I also encountered this problem, how did you solve it?

Was this page helpful?
0 / 5 - 0 ratings