I have a json string, which I should deSerialize to the following class
class Data <T> {
int found;
Class<T> hits
}
How do I do it? This is the usual way
mapper.readValue(jsonString, Data.class);
But how do I mention what T stands for?
if you're using scala and know the generic type at compile time, but don't want to manually pass TypeReference everywhere in all your api l ayers, you can use the following code (with jackson 2.9.5):
def read[T](entityStream: InputStream)(implicit typeTag: WeakTypeTag[T]): T = {
}
which can be used like this:
read[List[Map[Int, SomethingToSerialize]]](inputStream)
You need to create a
TypeReference
object for each generic type you use and use that for deserialization. For example,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:Then when you deserialize, you will find jackson has deserialize your data into a class which your variable hits actually is at runtime.
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 ofTypeReference
dynamically. Other questions referenced may already mention this, but it should look something like:Just write a static method in Util class. I am reading a Json from a file. you can give String also to readValue
Usage:
You can wrap it in another class which knows the type of your generic type.
Eg,
Here Something is a concrete type. You need a wrapper per reified type. Otherwise Jackson does not know what objects to create.