2

我正在尝试使用 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 {

有任何想法吗?

4

2 回答 2

1

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

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

@XmlElementRef
public AmazonContent Content;

了解更多信息:

于 2013-07-09T10:45:05.897 回答
0

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

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

XmlReference 应按如下方式参数化

抽象类指向here:

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或任何东西

希望能帮助到你!

于 2013-07-09T14:08:14.873 回答