XStream序列化和反序列化中的多态性 [英] Polymorphism in XStream serialization and deserialization

查看:135
本文介绍了XStream序列化和反序列化中的多态性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这些课程:

@XStreamAlias("person")
public class PersonConfig {

    private AnimalConfig animalConfig;

}

public interface AnimalConfig {}

@XStreamAlias("dog");
public class DogConfig extend AnimalConfig {}

@XStreamAlias("cat");
public class CatConfig extend AnimalConfig {}

我希望能够反序列化这个包含上述类的xml:

And I would like to be able to deserialize this xml with the classes above:

<person>
    <dog/>
<person>

除了反序列化这个xml,使用相同的类:

As well as deserialize this xml too, with the same classes:

<person>
    <cat/>
<person>

因此,在这两种情况下, PersonConfig 字段 animalConfig 已填写。在带有 DogConfig 实例的第一个XML中,在带有 CatConfig 实例的第二个XML中。

So that in both cases, the PersonConfig's field animalConfig is filled. In the first XML with a DogConfig instance and in the second XML with a CatConfig instance.

这是否可以通过添加一些注释来实现这个功能?

Is this possible by adding some annotation to make this work?

推荐答案

看来XStream确实如此不允许你轻易做到。

It seems XStream does not allow you to do it easily.

你的问题类似于这个,要求使用XStream管理类似xsd:choice的内容。

Your question is similar to this one, asking for managing something like a xsd:choice with XStream.

如果你不一定需要使用XStream,JAXB将允许您轻松完成:

If you don't necessarily need to use XStream, JAXB will allow you to do it easily :

@XmlRootElement(name="person")
public class PersonConfig {

    private AnimalConfig animalConfig;

    @XmlElementRefs({
        @XmlElementRef(name="cat", type=CatConfig.class),
        @XmlElementRef(name="dog", type=DogConfig.class)
    })
    public AnimalConfig getAnimalConfig() {
        return animalConfig;
    }

    public void setAnimalConfig(AnimalConfig animalConfig) {
        this.animalConfig = animalConfig;
    }
}

经过一些研究,列出了您房产的所有可用类别如果您选择使用 XmlAdapter ,则可以避免。
在Blaise Doughan链接中,该示例使用抽象类,而不是接口。

After some researches, listing all available classes for your property can be avoided if you choose to use the XmlAdapter. In Blaise Doughan link, the example uses an abstract class, not an interface.

编辑:

正如Blaise Doughan在评论中所说, @XmlElementRef 更适合此目的。代码已相应更新。

As Blaise Doughan said in its comment, @XmlElementRef is better suited for this purpose. Code has been updated accordingly.

这篇关于XStream序列化和反序列化中的多态性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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