简体   繁体   中英

How to deserialize nested generic class using Jackson Databind?

I want to deserialize JSON to a generic class (eg Foo) using Jackson's Object Mapper. First, I use this:

JavaType type = mapper.getTypeFactory().constructParametricType(valueType, valueInnerType);
Foo<Bar> response = mapper.readValue(inStream, type);

When everything is typed, everything is good! But I want to generalize the method that deserialize these objects. For example, with the same method, I want to deserialize an object of the Foo2 class and an object of the Foo class, everything with the same method.

I could do two generic methods:

public <T> T deserialize(Stream inStream, Class<T> classLiteral);
public <T, TInner> ??? deserialize(Stream inStream, Class<T> classLiteral, Class<TInner> innerClassLiteral);

But I don't know what type, I should return.

Is this the right way? Or there is a better way to do this?

If you like to write a general method to deserialize nested generic class using Jackson Databind, you can use TypeReference Object like this :

public <T> T deserialize(Stream inStream, TypeReference<T> typeReference){
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.readValue(inStream, typeReference);
}

and in your case you can use it like this:

Foo<Bar> response = deserialize(inStream, new TypeReference<Foo<Bar>>(){});

So by TypeReference Object you can write a general method and you can pass your generic class and your inner class by TypeReference.

If you like to read more about it you can find some sample about TypeReference in this link:

https://www.programcreek.com/java-api-examples/org.codehaus.jackson.type.TypeReference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM