JAXB引用的对象未正确反序列化

时间:2018-02-16 20:32:22

标签: java serialization jaxb

我正在尝试从JAX-RS Web服务反序列化收到的实体,但是无法成功地为参考字段执行此操作。传递的xml格式为:

<?xml version="1.0" encoding="UTF-8"?>
<linkReaderImpl>
   <name>DPIa0Nffg0WEBCLIENTt0Nffg0</name>
   <source>DPIa0Nffg0</source>
   <destination>WEBCLIENTt0Nffg0</destination>
   <latency>0</latency>
   <throughput>0.0</throughput>
</linkReaderImpl>

LinkReaderImpl 类看起来像:

@XmlRootElement
@XmlAccessorType( XmlAccessType.FIELD)
public class LinkReaderImpl extends NamedEntityReaderImpl implements LinkReader, Serializable{

    @XmlElement @XmlIDREF
    private NodeReaderImpl source;

    @XmlElement @XmlIDREF
    private NodeReaderImpl destination;

    private int latency;

    private float throughput;

    public void setLatency(int latency) {
        this.latency = latency;
    }

    public void setThroughput(float throughput) {
        this.throughput = throughput;
    }


    public LinkReaderImpl() {
        super(null);
        this.source = null;
        this.destination = null;
        this.latency = 0;
        this.throughput = 0;
    }
    @Override
    public NodeReader getSourceNode() {
        return this.source;
    }


    public void setSource(NodeReaderImpl source) {
        this.source = source;
    }

    @Override
    public NodeReader getDestinationNode() {
        return this.destination;
    }

    public void setDestination(NodeReaderImpl destination) {
        this.destination = destination;
    }

    @Override
    public int getLatency() {
        return this.latency;
    }

    @Override
    public float getThroughput() {
        return this.throughput;
    }

}

完成后:

LinkReaderImpl returnReader = response.readEntity(LinkReaderImpl.class);

名称,延迟,吞吐量等元素成功反序列化。但是,源和目标总是最终为空,尽管显然正在按预期编组和解组。这是一个简单的问题还是我完全误解了id / idref功能?

1 个答案:

答案 0 :(得分:0)

为了实现这一点,NodeReaderImpl需要有一个用@XmlID注释的属性,并且XML中应该有相应的元素。您发布的XML没有NodeReaderImpl个ID为DPIa0Nffg0WEBCLIENTt0Nffg0的元素。因此,JAXB找不到引用的对象,并将null分配给sourcedestination属性。

有关@XmlID / @XmlIDREF的更多信息,请参阅:

  

http://blog.bdoughan.com/2010/10/jaxb-and-shared-references-xmlid-and.html

您也可以使用IDResolver,请参阅:

  

https://stackoverflow.com/a/26607053/303810