How to use JAXB annotations using Spring RestTemplate?

I am trying to automatically deserialize a formatted XML response using Spring RestTemplate. I am using the Jackson module jackson-dataformat-xmlfor which Spring Boot is configured to automatically configure. I want to use JAXB annotations in a class that I want to use for deserialization, but it will not work. Here is an example of what I want the class to look like this:

@XmlRootElement(name="Book")
public class Book {

    @XmlElement(name="Title")
    private String title;
    @XmlElement(name="Author")
    private String author;

}

This is based on the following XML example:

<Book>
    <Title>My Book</Title>
    <Author>Me</Author>
</Book>

However, if the class is annotated as described above, the fields are always set null. I did some experimentation and found out that deserialization works if I use Jackson @JsonPropertyto annotate children:

@XmlRootElement(name="Book")
public class Book {

    @JsonProperty("Title")
    private String title;
    @JsonProperty("Author")
    private String author;

}

, - , . , JAXB , ?

Jackson jackson-module-jaxb-annotations XML- JAXB. , ObjectMapper RestTemplate .

+4
2

, JaxbAnnotationModule ObjectMapper, , Spring RestTemplate. Jackson jackson-module-jaxb-annotations, Gradle.

, , , RestTemplate, . ObjectMapper MappingJackson2XmlHttpMessageConverter, Spring. JaxbAnnotationModule ObjectMapper, , MappingJackson2XmlHttpMessageConverter, :

//create module
JaxbAnnotationModule jaxbAnnotationModule = new JaxbAnnotationModule();

restTemplate.getMessageConverters().stream().filter(converter -> {
    return converter instanceof MappingJackson2XmlHttpMessageConverter;
})

, ObjectMappers:

forEach(converter -> {
    ((MappingJackson2XmlHttpMessageConverter) converter)
            .getObjectMapper()
            .register(jaxbAnnotationModule);
});
+1

, Spring JAXB , .

JAXB, jackson-xc

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-xc</artifactId>
</dependency>

:

1) http://wiki.fasterxml.com/JacksonJAXBAnnotations

2) http://springinpractice.com/2011/12/06/jackson-json-jaxb2-xml-spring

3) Jackson RestTemplate?

+1

Source: https://habr.com/ru/post/1664587/


All Articles