xmlhttprequest—为什么jaxb不将这个xml文档解包成java对象?

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

感谢您抽出时间阅读。
在问之前,我想指出的是,我在stackoverflow/互联网上读过尽可能多的类似帖子。
我的目标是将api请求的响应反序列化为可用的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>

但是,当我试图将其解组到pojo中时,Map并没有按预期工作。
为了简单起见,我尝试只捕获第一个字段,id、title和source(我只捕获了一个字段id,而且我还尝试了所有字段都没有用)。
下面是pojo的样子:

@XmlRootElement(name = "entry", namespace = "http://purl.org/atom/ns#")
@XmlAccessorType(XmlAccessType.FIELD)
public class Response {

    @XmlElement(name = "id")
    private String id;

    @XmlElement(name = "title")
    private String title;

    @XmlElement(name = "source")
    private String source;

    public Response() {}
}

为了检查是否捕获了xml元素,我记录了属性,这些属性为null:

Response{id='null', title='null', source='null'}

feign是发送请求的http客户端,下面是客户端文件:

@FeignClient(name="ReportSchedulerClient", url = "https://scheduler.com", configuration = FeignClientConfiguration.class)
public interface ReportSchedulerClient {

    @PostMapping(value = "/webservice", consumes = "application/xml", produces = "text/xml")
    Response sendJobConfigRequest(@RequestBody Request request);

}

以及一个用于身份验证的简单自定义配置文件:

public class FeignClientConfiguration {
    @Bean
    public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
        return new BasicAuthRequestInterceptor("user", "pass");
    }
}

我试图避免显式地取消文件的编组,但我也尝试使用如下方式显式地取消请求的编组:

Response response = (Response) unmarshaller.unmarshal(new StreamSource(new StringReader(response.body().toString())));

请让我知道如果你有任何建议,如果我的代码有任何问题,或任何其他建议。提前谢谢。

2cmtqfgy

2cmtqfgy1#

您需要指定 namespace 在元素级别。例如:

@XmlElement(name = "id", namespace = "http://purl.org/atom/ns#")
private String id;

要设置默认名称空间,可以在包级别进行,在包文件夹中创建package-info.java文件,其内容如下:

@XmlSchema(
    namespace = "http://purl.org/atom/ns#",
    elementFormDefault = XmlNsForm.QUALIFIED)
package your.model.package;

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

除此之外,正如您明确添加的 @XmlElement 对于所有字段,可以删除 @XmlAccessorType(XmlAccessType.FIELD) 注解,因为它的目的是在默认情况下将所有字段Map到元素。

相关问题