Sure, here’s the translation: Java 多态 JSON 反序列化

huangapple go评论106阅读模式
英文:

Java Polymorphic Json Deserialization

问题

我在项目(Spring Java)中使用Jackson来进行序列化和反序列化。在通常情况下,当我在POJO中的字段中使用接口(契约)时,我会使用@JsonTypeInfo@JsonSubTypes来实现多态情况下的反序列化。但是,现在我有一个类似这样的场景:

public class classA {

    private contractA fieldA;

    // 构造函数和Getter-Setter方法
}

然后是:

public interface contractA {
}

最后是:

@JsonTypeInfo(
        use = JsonTypeInfo.Id.NAME,
        property = "type")
@JsonSubTypes({
        @JsonSubTypes.Type(/* 具体类1作为name-value */),
        @JsonSubTypes.Type(/* 具体类2作为name-value */),
})
public interface contractB extends contractA {
    // 契约方法
}

现在,当将classA作为控制器请求体传递,并且我将fieldA设置为具体类1具体类2时,Jackson不使用JsonSubTypes来进行反序列化为其中一个。我之所以这样做,并且有两个契约,是因为存在包依赖关系。contractBcontractA所在的包不同。

如何在contractA上配置Jackson,以指定该类在其子类中具有JsonSubTypeInfo?或者,欢迎提供其他库或方法。

谢谢!

英文:

I am using jackson as part of serializing and deserializing in my project (Spring Java).
In normal scenarios where I have interface(contract) acting as field in POJO,
then I use @JsonTypeInfo and @JsonSubTypes to achieve deserialization in polymorphic cases.
But, right now, I have scenariio something like this:

public class classA {

    private contractA fieldA;
    
    //constructor and getter-setters.
}

then,

public interface contractA {
}

and finally,

@JsonTypeInfo(
        use = JsonTypeInfo.Id.NAME,
        property = "type")
@JsonSubTypes({
        @JsonSubTypes.Type(/* concrete-class1 as name-value */),
        @JsonSubTypes.Type(/* concrete-class2 as name-value */),
})
public interface contractB extends contractA {
    //contract methods.
}

Now, when classA is passed as controller request body and I pass fieldA as concrete-class1 or concrete-class2,
JsonSubTypes are not being used by jackson to deserialize into one of them.
The reason why I did this and had two contracts is due to package dependencies. contractB
is in different package as of contractA's.
How can I configure on contractA using jackson that this class has its JsonSubTypeInfo specified in its subclasses.

Or, any other libraries or approaches are also welcomed.

Thank you !

答案1

得分: 0

这个问题后来通过引入我们自己的定制 JsonTypeInfo 来解决。

当应用程序在部署中时,我们会获取所有在 JsonTypeInfo 注解中(类似于 jackson 的自定义注解)存在的子类,并维护一个数据结构,该结构将在 序列化反序列化 时使用。这个过程在某种程度上类似于 Jackson(还包括查找嵌套层次结构)。

英文:

This problem is later on solved by introducing our own custon JsonTypeInfo.

When the application is under deployment, we fetch all subclasses which is present in the JsonTypeInfo annotation (jackson like custom annotaion) and maintain a data-structure, that will be used while serializing and deserializing. This process is somewhat similar to the Jackson one (in addition to lookup for nested hierarches as well).

huangapple
  • 本文由 发表于 2020年8月29日 00:15:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/63637490.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定