Jackson - Deserialize using generic class

jackson serialize generic type
jackson custom deserializer generic type
jackson serialize generic object
deserialize generic type java
jackson polymorphic deserialization
jackson deserialize interface
jackson deserialize string to array
type inference jackson

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?

You need to create a TypeReference object for each generic type you use and use that for deserialization. For example,

mapper.readValue(jsonString, new TypeReference<Data<String>>() {});

Deserialization Not Working Right with Generic Types and Builders , My main suggestion is really to avoid ever using generic types as root value (that is, then deserialization with jackson works out of the box: 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.

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);
}

Serialising generic value classes via Reference Types (like Optional , Instead we can have concrete java object and type cast it to be used in JSON binding. Consider the following example with a class UserData, a class to hold user  Jackson JSON Generic Serializing and Deserializing Methods. I was using the Jackson JSON library this week and wanting to be able to write a serialize and deserialize method that would work on a generic object.

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.

Jackson - Data Binding With Generics, Jackson – Deserialize using generic class. Posted by: admin December 20, 2017 Leave a comment. Questions: I have a json string, which I should deSerialize  The first is that I am passing the class type into the methods so the objectmapper knows the type that should deserialize. Is there a better way using generics? Unfortunately not, and this is because of type erasure. Also in the get method I am casting an object returned from the objectMapper to T.

For class Data<>

ObjectMapper mapper = new ObjectMapper();
JavaType type = mapper.getTypeFactory().constructParametrizedType(Data.class, Data.class, Parameter.class);
Data<Parameter> dataParam = mapper.readValue(jsonString,type)

Jackson - Deserialize using generic class, A generic java type can be defined which Jackson can use to generate json of the type shown above, consider the following Java generic type:  So for the above class structure and T can be of Type T1,T2 class. So to deserialize for AgentResponse, use the following code . JavaType javaType = objectMapper.getTypeFactory.constructParametricType(AgentResponse.class,T1.class) AgentResponse<T1> agentResponseT1 = objectMapper.readValue(inputJson,javaType);

Just write a static method in Util class. I am reading a Json from a file. you can give String also to readValue

public static <T> T convertJsonToPOJO(String filePath, Class<?> target) throws JsonParseException, JsonMappingException, IOException, ClassNotFoundException {
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.readValue(new File(filePath), objectMapper .getTypeFactory().constructCollectionType(List.class, Class.forName(target.getName())));
}

Usage:

List<TaskBean> list =  Util.<List<TaskBean>>convertJsonToPOJO("E:/J2eeWorkspaces/az_workspace_svn/az-client-service/dir1/dir2/filename.json", TaskBean.class);

Json deserialization with Jackson and Super type tokens, TypeReference should be instantiated using anonymous class; You should provide generic explicity. Failing to do so may lead to loss of generic type argument  Instead of T, you'll need to explicitly declare what class is used for the generic (i.e. objectMapper.readValue(jacksonString, MyObject<SomeClass>.class) – Jace J McPherson Oct 10 '16 at 23:10. Because Java generics use type erasure, MyObject.class and MyObject<T>.class are the very same class object.

Deserialize JSON collection to collection of Objects using Jackson, I was using the Jackson JSON library this week and wanting to be able to write a serialize and deserialize method that would work on a generic object. Next I created two classes that will allow us to test our generic json  This JSON can then be deserialized into generic class Foo.class just as you would deserialize any other class. ObjectMapper mapper = ; Foo<Bar1> foo = new Foo<Bar1>(); String json = objectMapper.writeValueAsString(foo); foo = mapper.readValue(json, Foo.class); // no need to specify the type Bar1.

Jackson JSON Generic Serializing and Deserializing Methods , JSON, Gson, and Java: take a look at this handy tutorial on If we dealt with a class without generics, our code deserializing the string  A tutorial that shows you how to deserialize and unmarshal a JSON query using Jackson, as well as how to reserialize from JSON, and what to look out for. Custom JSON Deserialization With Jackson

Gson: Deserialization of Generic Types, How to map a JSON Array correctly in a type-safe manner to a Java Collection. to deserialize a JSON Array to a Java Array or Collection with Jackson 2. Jackson will not be able to get the full generic type information and  Jackson - Serialize objects with LocalDate (default) This example uses a more realistic Java Class, in this case using a LocalDate field (introduced in Java 8). To be able to serialize those objects in a meaningful way, you need to register the JavaTimeModule, contained in the dependency library  jackson-datatype-jsr310.

Comments
  • possible duplicate of Jackson - Deserialize Generic class variable
  • see stackoverflow.com/questions/17400850/…
  • I have to use it as TypeReference<Data<T>>(){} ... But I am getting the following error - cannot access private java.lang.class.Class() from java.lang.class. Failed to set access. Cannot make a java.lang.Class constructor accessible
  • No, not Data<T>, that is NOT a type. You must specify actual class; otherwise it is same as Data<Object>.
  • What if I dont know what class it is until runtime? I will get the class as a parameter during runtime. Like this public <T> void deSerialize(Class<T> clazz { ObjectMapper mapper = new ObjectMapper(); mapper.readValue(jsonString, new TypeReference<Json<T>>() {}); }
  • I have asked the full question correctly here stackoverflow.com/questions/11659844/…
  • What if I dont know what class it is until runtime? I will get the class as a parameter during runtime. Like this public <T> void deSerialize(Class<T> clazz { ObjectMapper mapper = new ObjectMapper(); mapper.readValue(jsonString, new TypeReference<Json<T>>() {}); }
  • I have asked the full question here stackoverflow.com/questions/11659844/…
  • Then just pass the class as is, no need for TypeReference: return mapper.readValue(json, clazz); What exactly is the problem here?
  • The problem is that "Data" is a generic class. I need to specify what type T is at runtime. The parameter clazz is what T us at runtime. So, how to call readValue? calling it with new TypeReference>Json<T>> does not work The full question is here stackoverflow.com/questions/11659844/…
  • Ok. Then you need to use TypeFactory.. I will edit my answer.
  • and how do I manage this if I want to have a List? Like let's say List<ImageResult>