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

查看:33
本文介绍了基于唯一属性的存在使用 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 的名称"和值"属性来完成您想要的操作.反序列化器和 @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天全站免登陆