簡體   English   中英

當有 2 個命名空間時,如何使用 JAXB 解組對 2 個 java 對象的 XML 響應?

[英]How can I unmarshal an XML response to 2 java objects using JAXB when there are 2 namespaces?

感謝您花時間閱讀。

我的目標是將來自 API 請求的響應反序列化為 2 個可用的 java 對象。

我正在向端點發送一個 POST 請求,以在我們的計划中創建一個作業。 作業創建成功,正文中返回以下 XML:

<entry xmlns="http://purl.org/atom/ns#">
    <id>0</id>
    <title>Job has been created.</title>
    <source>com.tidalsoft.framework.rpc.Result</source>
    <tes:result xmlns:tes="http://www.auto-schedule.com/client">
        <tes:message>Job has been created.</tes:message>
        <tes:objectid>42320</tes:objectid>
        <tes:id>0</tes:id>
        <tes:operation>CREATE</tes:operation>
        <tes:ok>true</tes:ok>
        <tes:objectname>Job</tes:objectname>
    </tes:result>
</entry>

當我嘗試僅捕獲元素idtitlesource時,數據被成功捕獲。 問題是當我引入子 object 時,它試圖捕獲tes:result元素中的數據。

這是父 POJO 的樣子:

@XmlRootElement(name = "entry")
@XmlAccessorType(XmlAccessType.FIELD)
public class Response {

    private String id;

    private String title;

    private String source;

    ResponseDetails result;

    public Response() {}
}

這是子 object:

@XmlAccessorType(XmlAccessType.FIELD)
public class ResponseDetails {

    @XmlElement(name = "tes:message")
    String message;
    
    @XmlElement(name = "tes:objectid")
    String objectid;

    @XmlElement(name = "tes:operation")
    String operation;

    @XmlElement(name = "tes:ok")
    String ok;

    @XmlElement(name = "tes:objectname")
    String objectname;
}

最后,這是我正在使用的 package-info.java 文件:

@XmlSchema(
        namespace = "http://purl.org/atom/ns#",
        elementFormDefault = XmlNsForm.QUALIFIED)
package com.netspend.raven.tidal.request.response;

import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;

任何想法都非常感謝。 謝謝。

問題是:您的 Java 代碼未正確指定與內部 XML 元素對應的命名空間

<tes:result xmlns:tes="http://www.auto-schedule.com/client">
    <tes:message>Job has been created.</tes:message>
    <tes:objectid>42320</tes:objectid>
    <tes:id>0</tes:id>
    <tes:operation>CREATE</tes:operation>
    <tes:ok>true</tes:ok>
    <tes:objectname>Job</tes:objectname>
</tes:result>

<tes:result> XML 元素具有命名空間"http://www.auto-schedule.com/client" 命名空間前綴tes:本身與 Java 無關。 (發明 XML 命名空間前綴只是為了提高 XML 代碼的可讀性。)因此在您的Response class 中,而不是僅僅寫

ResponseDetails result;

你需要寫

@XmlElement(namespace = "http://www.auto-schedule.com/client")
ResponseDetails result;

另請參見XmlElement.namespace的 javadoc。

此外, <tes:result>中的所有 XML 子元素都使用此命名空間"http://www.auto-schedule.com/client"指定。 因此,在您的ResponseDetails中,您還必須更正命名空間的內容。 例如,而不是

@XmlElement(name = "tes:message")
String message;

你需要寫

@XmlElement(name = "message", namespace = "http://www.auto-schedule.com/client")
String message;

您也可以省略name = "message"並簡單地寫

@XmlElement(namespace = "http://www.auto-schedule.com/client")
String message;

因為 JAXB 從您的 Java 屬性名稱message中獲取此名稱。

與此 class 中的所有其他屬性類似。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM