当有2个名称空间时,如何使用jaxb解组对2个java对象的xml响应?

ifmq2ha2  于 2021-06-26  发布在  Java
关注(0)|答案(1)|浏览(305)

感谢您抽出时间阅读。
我的目标是将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>

当我尝试只捕获元素id、title和source时,数据被成功捕获。问题是当我引入子对象时,它试图捕获tes:result element.
父pojo是这样的:

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

    private String id;

    private String title;

    private String source;

    ResponseDetails result;

    public Response() {}
}

下面是子对象:

@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;

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

chy5wohz

chy5wohz1#

问题是: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 上课,而不仅仅是写作

ResponseDetails result;

你需要写信

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

另请参见 XmlElement.namespace .
还有 <tes:result> 使用此命名空间指定 "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 .
对于这个类中的所有其他属性也是类似的。

相关问题