如何在从端点返回的xml中添加XML声明

时间:2016-08-21 23:39:31

标签: xml spring-boot

我已将以下内容添加到我的应用程序

@Bean
public MappingJackson2XmlHttpMessageConverter mappingJackson2XmlHttpMessageConverter() {
    MappingJackson2XmlHttpMessageConverter xmlConverter = new MappingJackson2XmlHttpMessageConverter();
    XmlMapper objectMapper = new XmlMapper();
    objectMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
    xmlConverter.setObjectMapper(objectMapper);
    return xmlConverter;
}

但是,xml返回如下,即缺少xml声明。任何想法我需要添加什么?

<Data>
<description></description>
<codeList>
    <codeList>
        <description>User ID</description>
        <key>dfdfeee</key>
    </codeList>
    <codeList>
        <description>Activation ID</description>
        <key>2ddddd9881</key>
    </codeList>
</codeList>

2 个答案:

答案 0 :(得分:2)

声明bean:

@Bean
public MappingJackson2XmlHttpMessageConverter mappingJackson2XmlHttpMessageConverter(Jackson2ObjectMapperBuilder builder) {
    XmlMapper xmlMapper = builder.createXmlMapper(true).build();
    xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
    return new MappingJackson2XmlHttpMessageConverter(xmlMapper);
}

BTW,这应该覆盖

中自动配置的bean
org.springframework.boot.autoconfigure.web.JacksonHttpMessageConvertersConfiguration.MappingJackson2XmlHttpMessageConverterConfiguration

此外,这种方式应该应用所有XmlMapper / ObjectMapper自定义,如果你有。

答案 1 :(得分:0)

也许您可以尝试使用@Order(1),它将替换默认的bean。

@Configuration
@Order(1)
public class HttpMessageConverterConfig {

    @Bean
    public MappingJackson2XmlHttpMessageConverter mappingJackson2XmlHttpMessageConverter(
            Jackson2ObjectMapperBuilder builder) {
        XmlMapper xmlMapper = builder.createXmlMapper(true).build();
        xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
        return new MappingJackson2XmlHttpMessageConverter(xmlMapper);
    }

}