感谢您抽出时间阅读。
在提问之前,我想指出的是,我在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时,映射并没有按预期工作。
为了简单起见,我尝试只捕获第一个字段,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);
}
和一个简单的auth:自定义配置文件
public class FeignClientConfiguration {
@Bean
public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
return new BasicAuthRequestInterceptor("user", "pass");
}
}
我试图避免显式地对文件进行解组,但我也尝试过使用以下内容显式地解组请求:
Response response = (Response) unmarshaller.unmarshal(new StreamSource(new StringReader(response.body().toString())));
如果你有任何建议,如果我的代码有任何问题,或者任何其他建议,请告诉我。提前谢谢。
您需要在元素级别指定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)
注释,因为它的目的是在默认情况下将所有字段映射到元素。