基于独特属性的存在,使用Jackson来反序列化多态类型 [英] Deserializing polymorphic types with Jackson based on the presence of a unique property

查看:101
本文介绍了基于独特属性的存在,使用Jackson来反序列化多态类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样的类结构:

If I have a class structure like so:

public abstract class Parent {
    private Long id;
    ...
}

public class SubClassA extends Parent {
    private String stringA;
    private Integer intA;
    ...
}

public class SubClassB extends Parent {
    private String stringB;
    private Integer intB;
    ...
}

是否存在另一种反序列化不同于@JsonTypeInfo的方法?在父类上使用此注释:

Is there an alternative way to deserialize different then @JsonTypeInfo? Using this annotation on my parent class:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "objectType")

我宁愿不必强制我的API的客户端包括"objectType": "SubClassA"来反序列化Parent子类.

I would rather not have to force clients of my API to include "objectType": "SubClassA" to deserialize a Parent subclass.

Jackson是否提供一种方法来注释子类并通过独特的属性将其与其他子类区分开,而不是使用@JsonTypeInfo?在上面的示例中,这类似于如果JSON对象将"stringA": ...反序列化为SubClassA,如果它将"stringB": ...反序列化为SubClassB".

Instead of using @JsonTypeInfo, does Jackson provide a way to annotate a subclass and distinguish it from other subclasses via a unique property? In my example above, this would be something like, "If a JSON object has "stringA": ... deserialize it as SubClassA, if it has "stringB": ... deserialize it as SubClassB".

推荐答案

这似乎应该使用@JsonTypeInfo@JsonSubTypes的东西,但是我选择了文档,但没有提供任何可以完全提供的属性似乎符合您的描述.

This feels like something @JsonTypeInfo and @JsonSubTypes should be used for but I've picked through the docs and none of the properties that can be supplied quite seem to match what you're describing.

您可以编写一个自定义反序列化器,以非标准方式使用@JsonSubTypes'"name"和"value"属性来完成所需的操作.将在您的基类上提供反序列化器和@JsonSubTypes,反序列化器将使用名称"值检查属性是否存在,如果存在,则将JSON反序列化为值"属性中提供的类.然后您的课程将如下所示:

You could write a custom deserializer that uses @JsonSubTypes' "name" and "value" properties in a non-standard way to accomplish what you want. The deserializer and @JsonSubTypes would be supplied on your base class and the deserializer would use the "name" values to check for the presence of a property and if it exists, then deserialize the JSON into the class supplied in the "value" property. Your classes would then look something like this:

@JsonDeserialize(using = PropertyPresentDeserializer.class)
@JsonSubTypes({
        @Type(name = "stringA", value = SubClassA.class),
        @Type(name = "stringB", value = SubClassB.class)
})
public abstract class Parent {
    private Long id;
    ...
}

public class SubClassA extends Parent {
    private String stringA;
    private Integer intA;
    ...
}

public class SubClassB extends Parent {
    private String stringB;
    private Integer intB;
    ...
}

这篇关于基于独特属性的存在,使用Jackson来反序列化多态类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆