我使用spring-web
向网络服务发送POST
个xml请求。但是我的Xml bean请求没有呈现我使用jaxb
属性定义它的方式:
//this class is autogenerated with xsdtojava from *.xsd files
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "myRequest")
public class ServletRequest {
@XmlAttribute(name = "age")
private int age;
}
用法:
ServletRequest req = new ServletRequest();
req.setAge(20);
restTemplateBuilder.build().postForEntity(url, new HttpEntity<>(req), MyRsp.class);
发送的结果xml:
<ServletRequest>
<age>20</age>
</ServletRequest>
问题:@XmlRootElement
名称和@XmlAttribute
注释似乎都被忽略了。为什么呢?
答案 0 :(得分:0)
@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson() {
return new Jackson2ObjectMapperBuilderCustomizer() {
@Override
public void customize(Jackson2ObjectMapperBuilder builder) {
builder.modules(new JaxbAnnotationModule());
}
};
}
甚至更短的java8:
@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson() {
return (builder) -> builder.modules(new JaxbAnnotationModule());
}
从杰克逊2.9.0
开始,这是杰克逊核心库的一部分。
之前,您必须添加:
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jaxb-annotations</artifactId>
<version>2.8.x</version>
</dependency>