springboot接收并响应xml

一、引包


    com.fasterxml.jackson.dataformat
    jackson-dataformat-xml
    2.9.7

二、配置XML转换器

@Configuration
public class MessageConverterConfig extends WebMvcConfigurationSupport {

    @Override
    public void configureMessageConverters(List> converters) {
        Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.xml();
        builder.indentOutput(true);
        converters.add(new MappingJackson2XmlHttpMessageConverter(builder.build()));
    }
}

三、controller层

@RequestMapping(value = "/creditLoanApplyNotify", method = RequestMethod.POST,consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE)
    @ResponseBody
    public String creditLoanApplyNotify(@RequestBody CreditLoanApplyNotifyDto req) {
// 自己逻辑
}

四、响应的XML没有xml头

这种:

起作用的是: xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);

 XmlMapper xmlMapper = new XmlMapper();
        xmlMapper.setDefaultUseWrapper(false);
        xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
        String requestBody  = xmlMapper.writeValueAsString(req);

五、对于复杂的xml

比如xml长这样:



    
        
            ANK85
            apply.notify
            UTF-8
            201803300309471966
            1.0.0.20180621
            201909191
            UTC+8
            RSA
            1.0.0
        
        
            2018033
            A
            
                000
                sign check fail
                N
            
        
    
    arfLohOxOIL0BOry==

处理示例:

@JacksonXmlRootElement(localName = "document")
@Data
public class CreditLoanApproveAckNotifyDto {
    @JacksonXmlElementWrapper(localName ="request")
    private Request request;
    @JacksonXmlProperty(localName = "signature")
    private String signature;

    @Data
    public class Request {
        @JacksonXmlElementWrapper(localName ="head")
        private Header head;
        @JacksonXmlElementWrapper(localName ="body")
        private NotifyDomain body;
    }
}

你可能感兴趣的:(Spring)