【问题标题】:JAXB Unmarshalling - A descriptor with default root element ... was not foundJAXB Unmarshalling - 未找到具有默认根元素的描述符...
【发布时间】:2019-07-09 19:38:36
【问题描述】:

我在将 api xml 响应解组为我创建的 POJO 时遇到问题。

我确信 JAXB 上下文知道我的类,因为我能够正确编组它。

POJO

package com.bnh.element.misc.Requests;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "selectionResponse")
@XmlAccessorType(XmlAccessType.FIELD)
public class SelectionResponse {
    @XmlElement
    boolean _hasErrors;
    @XmlElement
    int selectionIndex;
    @XmlElement
    String type;

}

尝试解组:

Object response = JAXB_CONTEXT.createUnmarshaller()
    .unmarshal( new StringReader(xml) );

抛出异常

[异常 [EclipseLink-25008] (Eclipse Persistence Services - 2.6.4.v20160829-44060b6): org.eclipse.persistence.exceptions.XMLMarshalException 异常描述:具有默认根元素的描述符 {http://tripos.vantiv.com/2014/09/TriPos.Api}selectionResponse 在项目中未找到] 在 org.eclipse.persistence.jaxb.JAXBUnmarshaller.handleXMLMarshalException(JAXBUnmarshaller.java:1110)

来自 API 的实际响应:

<selectionResponse
  xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://tripos.vantiv.com/2014/09/TriPos.Api">
  <_errors />
  <_hasErrors>false</_hasErrors>
  <_links />
  <_logs
    xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" i:type="Logs" />
    <_type>selectionResponse</_type>
    <_warnings />
    <selectionIndex>0</selectionIndex>
  </selectionResponse>

编组对象时生成的字符串:

<selectionResponse
    xmlns:ns0="http://tripos.vantiv.com/2014/09/TriPos.Api">
    <_hasErrors>false</_hasErrors>
    <selectionIndex>0</selectionIndex>
</selectionResponse>

任何帮助将不胜感激。谢谢!

【问题讨论】:

    标签: java xml namespaces jaxb unmarshalling


    【解决方案1】:

    你的错误说明了很多:

    异常说明:具有默认根元素的描述符 {http://tripos.vantiv.com/2014/09/TriPos.Api}selectionResponse 在项目中未找到]

    您的 xml 中的默认 xmlns 是:

      xmlns="http://tripos.vantiv.com/2014/09/TriPos.Api">
    

    它不能被“猜测”,所以将命名空间添加到你的根元素声明中,例如:

    @XmlRootElement(name = "selectionResponse",
        namespace="http://tripos.vantiv.com/2014/09/TriPos.Api")
    @XmlAccessorType(XmlAccessType.FIELD)
    public static class SelectionResponse {
    ...
    

    【讨论】:

    • @BHDev 无需感谢。如果您对我的回答感到满意,请勾选接受 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多