【问题标题】:JAXB referenced object not being deserialized correctlyJAXB 引用的对象未正确反序列化
【发布时间】:2018-02-16 20:32:22
【问题描述】:

我正在尝试反序列化从 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 功能?

【问题讨论】:

    标签: java serialization jaxb


    【解决方案1】:

    为此,NodeReaderImpl 需要有一个用@XmlID 注释的属性,并且您的 XML 中应该有相应的元素。您发布的 XML 没有 ID 为 DPIa0Nffg0WEBCLIENTt0Nffg0NodeReaderImpl 元素。所以 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

    【讨论】:

      猜你喜欢
      • 2021-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多