0 results found
DeCo
SpringBoot Web 接收和返回xml数据
2019/11/15 SpringBoot xml

添加pom依赖

<dependency>
   <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.8.8</version>
</dependency>

请求报文

<xml>
    <result_code><![CDATA[SUCCESS]]></result_code>
    <sign><![CDATA[781F357070A6DC1D64F3820B6D0635AF]]></sign>
    <mch_id>10010404</mch_id>
    <contract_code>100001256</contract_code>
    <openid><![CDATA[onqOjjmM1tad-3ROpncN-yUfa6ua]]></openid>
    <plan_id><![CDATA[123]]></plan_id>
    <change_type><![CDATA[ADD]]></change_type>
    <operate_time><![CDATA[2015-07-01 10:00:00]]></operate_time>
    <contract_id><![CDATA[Wx15463511252015071056489715]]></contract_id>
</xml>

1.使用对象接收

@Data
@JacksonXmlRootElement(localName = "xml")
public class TsContract {

    @JacksonXmlProperty(localName = "return_code")
    @JacksonXmlCData
    private String returnCode;

    @JacksonXmlProperty(localName = "sign")
    @JacksonXmlCData
    private String sign;

    @JacksonXmlProperty(localName = "mch_id")
    @JacksonXmlCData
    private String mchId;

    @JacksonXmlProperty(localName = "contract_code")
    @JacksonXmlCData
    private String contractCode;

    @JacksonXmlProperty(localName = "openid")
    @JacksonXmlCData
    private String openid;

    @JacksonXmlProperty(localName = "plan_id")
    @JacksonXmlCData
    private String planId;

    @JacksonXmlProperty(localName = "change_type")
    @JacksonXmlCData
    private String changeType;

    @JacksonXmlProperty(localName = "operate_time")
    @JacksonXmlCData
    private String operateTime;

    @JacksonXmlProperty(localName = "contract_id")
    @JacksonXmlCData
    private String contractId;
}

@JacksonXmlCData注解,在返回的数据加上<![CDATA[]]>

@PostMapping(value = "/xml", produces = MediaType.APPLICATION_XML_VALUE)
public TsContract xml(@RequestBody TsContract tsContract) throws JsonProcessingException {
    return tsContract;
}

2.使用字符串接收

@Data
@JacksonXmlRootElement(localName = "xml")
public class ReturnParam {

    @JacksonXmlProperty(localName = "return_code")
    @JacksonXmlCData
    private String returnCode;

    @JacksonXmlProperty(localName = "return_msg")
    @JacksonXmlCData
    private String returnMsg;
}
@PostMapping(value = "/xmlStr", produces = MediaType.APPLICATION_XML_VALUE)
public ReturnParam xmlStr(@RequestBody String body) throws IOException {
    ObjectMapper mapper = new XmlMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    Map<String, Object> map = mapper.readValue(body, new TypeReference<Map<String, Object>>() {
     });
     // 取值
     String sign = (String) map.get("sign");
     ReturnParam returnParam = new ReturnParam();
     returnParam.setreturnMsg("OK");
     returnParam.setreturnCode("SUCCESS");
     return returnParam;
}
请杯咖啡呗~
支付宝
微信
本文作者:DeCo
版权声明:本文首发于DeCo的博客,转载请注明出处!