【问题标题】:JAXB element showing the SuperClass name and the Class name as an attribute显示超类名称和类名称作为属性的 JAXB 元素
【发布时间】:2013-07-05 11:18:14
【问题描述】:

我正在尝试使用 JAXB 在 XML 中序列化一些对象,当我到达一个作为抽象类指针的字段时,我将这段代码序列化:

<Message>
    <MessageID>1</MessageID>
    <OperationType>Update</OperationType>
    **<Content xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="product">**
        <SKU>skuparent</SKU> ...

但我需要的是这样的:

<Message>
    <MessageID>1</MessageID>
    <OperationType>Update</OperationType>
    **<Product>**
        <SKU>skuparent</SKU>

而且我无法使用“@XMLTransient”标记对其进行转换,这是我从其他帖子中得到的唯一建议

我的代码是这样的:

@XmlType(propOrder = { "MessageID", "operationType", "Content"})
public static class message{
    public int MessageID;
    private String OperationType;
    @XmlElement(name ="OperationType")
    public String getOperationType() {
        return OperationType;
    }

    public void setOperationType(String _operationType) {
        OperationType = operationType.valueOf(_operationType).toString();
    }

    public AmazonContent Content;
}

“AmazonContent”是这样的抽象类:

@XmlSeeAlso({Product.class})
public abstract class AmazonContent {

}

子类实例是:

@XmlRootElement(name = "Product")
@XmlType(propOrder = { "SKU", "StandardProductID", "DescriptionData", "ProductData"})
public class Product extends AmazonContent {

有什么想法吗?

【问题讨论】:

    标签: xml jaxb marshalling hierarchy


    【解决方案1】:

    默认情况下,JAXB 实现在表示继承时将利用xsi:type 属性作为描述符节点:

    使用元素名称作为继承指示符对应于替换组的 XML 模式概念,可以使用 @XmlElementRef 注释进行映射。该值的元素名称将是在引用类的@XmlRootElement 注释中指定的名称。

    @XmlElementRef
    public AmazonContent Content;
    

    更多信息:

    【讨论】:

    • 完美的布莱斯!我开始吓坏了,我编写了所有补丁程序,以便进一步 XPath 寻找属性和交换名称。真丢人。
    【解决方案2】:

    Blaise Doughan 可能由于后来的 Api 更新而错过了一个细节,我在这里找到了:

    http://old.nabble.com/Re:-XmlElementRef-points-to-a-non-existent-class-p22366506.html

    XmlReference 的参数化如下

    抽象类指向这里:

    public static class productData{
        @XmlElementRefs({
            @XmlElementRef(type = Shoes.class),
            @XmlElementRef(type = Clothing.class)
        })
        public AmazonProductData Product; //Abstract AmazonProductData
    }
    

    这些是子类:

    @XmlRootElement(name = "Shoes")
    public class Shoes extends AmazonProductData {
    

    @XmlRootElement(name = "Clothing")
    public class Clothing extends AmazonProductData {
    

    不需要其他任何东西,也不需要 @XmlTransient,也不需要 @XmlSeeAlso 或任何东西

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-29
      • 2021-07-23
      相关资源
      最近更新 更多