Jackson多态性:如何将多个子类型映射到同一个类 [英] Jackson polymorphism: How to map multiple subtypes to the same class

查看:207
本文介绍了Jackson多态性:如何将多个子类型映射到同一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Jackson 1.9.x.
坚持动物示例,这是我想做的事情:

I'm using Jackson 1.9.x. Sticking with the Animals example, Here's what I'd like to do:

假设我有一个Animal类:

Let's say I have an Animal class:

public class Animal {
    private String type;
    // accessors
}

public class Mammal extends Animal {
    private String diet;
    // accessors
}

public class Bird extends Animal {
    private boolean tropical;
    // accessors
}

我希望能够做点什么像这样(我将一些子类型映射到一个类,并将一些子类型映射到另一个类):

I would like to be able to do something like this (where I map a few subtypes to one class, and a few more to a different class):

@JsonTypeInfo(use = Id.NAME, include = As.PROPERTY, property = "type")
@JsonSubTypes({@JsonSubTypes.Type(value = Mammal.class, name = "Dog"),
                @JsonSubTypes.Type(value = Mammal.class, name = "Cat"),
                @JsonSubTypes.Type(value = Bird.class, name = "Dodo"},
                @JsonSubTypes.Type(value = Bird.class, name = "Cockatoo"})
public class Animal {

}

我现在看到的是Jackson只会识别Dog-to-Mammal和Dodo-to-Bird映射。这是因为StdSubtypeResolver._collectAndResolve()只允许同一个类进行注册一次(由于NamedType.equals()的实现)。

What I'm seeing right now is that Jackson will only recognize the Dog-to-Mammal and the Dodo-to-Bird mapping. This is because StdSubtypeResolver._collectAndResolve() only allows the same class to get registered once (due to the implementation of NamedType.equals()).

我是否有解决方法?我看到了吗?

Is there a workaround to the issue I'm seeing?

推荐答案

也许不是通过使用注释。问题来自于这样的映射不适用于序列化,并且现有映射确实期望一对一(双射)关系。
但您可能想在 jackson-databind问题跟踪器上提交RFE;可能会增加支持。

Perhaps not by using annotations. Problems comes from the fact that such mapping would not work for serialization, and existing mapping does expect one-to-one (bijection) relationship. But you may want to file an RFE at jackson-databind issue tracker; adding support may be possible.

这篇关于Jackson多态性:如何将多个子类型映射到同一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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