如何在泛型中使用Jackson

如何在泛型中使用Jackson

本文介绍了如何在泛型中使用Jackson的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下对象结构:

I have the following object structure:

public class Animal<T> implements IMakeSound<T>
public class Dog<T> extends Animal<T>
public class Cat<T> extends Animal<T>

我想使用jackson对我的对象进行序列化和反序列化。问题是在Json中,我在T中获得了LinkedHashmap,而在反基础对象Animal中则是反序列化。

I want to serialize and de-serialize my object using jackson.
The problem is that in the Json I am getting a LinkedHashmap in the T and the de-sirializtion is to the base object Animal.

当我为T ie添加限制时,由于Jackson注释,它完美地工作

When I am adding restriction to the T i.e. than it works perfectly because of the Jackson annotations

@JsonSubTypes({
   @Type(value = PuffyTail.class, name = "puffyTail"),
   @Type(value = StraightTail.class, name = "straightTail") })
class Tail {
...

但那不是我想要的行为 - 我不使用< X延伸Y>。

But that is not the behavior that I wanted - I don't use < X extends Y >.

有没有办法使用java泛型并获得序列化的正确对象?

有没有办法在没有注释的情况下完成它?

Is there a way to work with java generics and get the right object that was serialized?
Is there a way to accomplish it without annotations?

推荐答案

当从ObjectMapper中读取值以解析正确类型的对象时,可以指定一个TypeReference:

You can specify a TypeReference when reading the value from your ObjectMapper in order to parse the correctly typed object:

Cat<PuffyTail> fluffyKitty = objectMapper.readValue(jsonString,
        new TypeReference<Cat<PuffyTail>>(){});

这篇关于如何在泛型中使用Jackson的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 13:39