简体   繁体   English

如何使用Jackson Databind反序列化嵌套的泛型类?

[英]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. 我想使用杰克逊的对象映射器将JSON反序列化为通用类(例如Foo)。 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. 例如,使用相同的方法,我想反序列化Foo2类的对象和Foo类的对象,所有方法都使用相同的方法。

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 : 如果您想使用Jackson数据绑定编写一个通用方法来反序列化嵌套的通用类,则可以使用TypeReference Object,如下所示:

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. 因此,通过TypeReference对象,您可以编写通用方法,并可以通过TypeReference传递通用类和内部类。

If you like to read more about it you can find some sample about TypeReference in this link: 如果您想了解更多有关它的信息,可以在此链接中找到一些有关TypeReference的示例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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