Jackson - Deserialize using generic class
You can't do that: you must specify fully resolved type, like Data<MyType>
. T
is just a variable, and as is meaningless.
But if you mean that T
will be known, just not statically, you need to create equivalent of TypeReference
dynamically. Other questions referenced may already mention this, but it should look something like:
public Data<T> read(InputStream json, Class<T> contentClass) { JavaType type = mapper.getTypeFactory().constructParametricType(Data.class, contentClass); return mapper.readValue(json, type);}
First thing you do is serialize, then you can do deserialize.
so when you do serialize, you should use @JsonTypeInfo
to let jackson write class information into your json data. What you can do is like this:
Class Data <T> { int found; @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class") Class<T> hits}
Then when you deserialize, you will find jackson has deserialize your data into a class which your variable hits actually is at runtime.