Springboot支持XML格式报文的传输

导入依赖-jackson-dataformat-xml

 <!--整合web模块-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--使用Undertow服务器-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-undertow</artifactId>
        </dependency>
        <!--支持xml格式报文-->
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
            <version>2.14.3</version>
        </dependency>

示例预设值请求XML格式

<?xml version="1.0" encoding="UTF-8" ?>
<request>
  <username>隔壁老郭</username>
  <activityId>9090960</activityId>
  <timestamp>1684470742</timestamp>
</request>

示例预设值响应XML格式

<resp>
	<code>200 Ok</code>
	<timestamp>1684500309</timestamp>
	<msg>很高兴认识你-白嫖老郭</msg>
	<requestCommon>
		<body>隔壁老郭</body>
		<activityId>9090960</activityId>
	</requestCommon>
</resp>

构建请求进来的对象VO

/**
 * @description: JSON-XML转化
 * @author: GuoTong
 * @createTime: 2023-05-19 10:37
 * @since JDK 1.8 OR 11
 **/
@Data
@JacksonXmlRootElement(localName = "request")
@NoArgsConstructor
@AllArgsConstructor
public class JsonToXMLChangeReq implements Serializable {

    // 用户名
    @JacksonXmlProperty(localName = "username")
    private String username;

    // 用户活动ID
    @JacksonXmlProperty(localName = "activityId")
    private String activityId;

    // 时间戳
    @JacksonXmlProperty(localName = "timestamp")
    private Long timestamp;

}

构建响应出去的对象VO:

注意这个响应体是多层级的XML格式

 * @description:
 * @author: GuoTong
 * @createTime: 2023-05-19 12:00
 * @since JDK 1.8 OR 11
 **/
@Data
public class RequestCommon implements Serializable {

    // 用户活动ID
    @JacksonXmlProperty(localName = "body")
    private String body;


    // 用户活动ID
    @JacksonXmlProperty(localName = "activityId")
    private String activityId;
}

/**
 * @description: JSON-XML转化
 * @author: GuoTong
 * @createTime: 2023-05-19 10:37
 * @since JDK 1.8 OR 11
 **/
@Data
@JacksonXmlRootElement(localName = "resp")
@NoArgsConstructor
@AllArgsConstructor
public class JsonToXMLChangeResp implements Serializable {

    // 状态码
    @JacksonXmlProperty(localName = "code")
    private String code;

    // 时间戳
    @JacksonXmlProperty(localName = "timestamp")
    private Long timestamp;

    // 响应描述
    @JacksonXmlProperty(localName = "msg")
    private String msg;

    private RequestCommon RequestCommon;
}

/**
 * @description:
 * @author: GuoTong
 * @createTime: 2023-05-19 12:00
 * @since JDK 1.8 OR 11
 **/
@Data
public class RequestCommon implements Serializable {

    // 用户活动ID
    @JacksonXmlProperty(localName = "body")
    private String body;


    // 用户活动ID
    @JacksonXmlProperty(localName = "activityId")
    private String activityId;
}

编写Controller

@PostMapping(value = "/xml",
            consumes = MediaType.APPLICATION_XML_VALUE,
            produces = MediaType.APPLICATION_XML_VALUE)
    @ResponseBody
    public String getCameraImageTest(@RequestBody JsonToXMLChangeReq jsonToXMLChange) {
        JsonToXMLChangeResp jsonToXMLChangeResp = new JsonToXMLChangeResp();
        jsonToXMLChangeResp.setCode("200");
        jsonToXMLChangeResp.setTimestamp(LocalDateTime.now().toEpochSecond(ZoneOffset.UTC));
        jsonToXMLChangeResp.setMsg("很高兴认识你-白嫖老郭");
        RequestCommon requestCommon = new RequestCommon();
        requestCommon.setActivityId(jsonToXMLChange.getActivityId());
        requestCommon.setBody(jsonToXMLChange.getUsername());
        jsonToXMLChangeResp.setRequestCommon(requestCommon);
        return JSONXMLUtils.serialize(jsonToXMLChangeResp);
    }

使用到工具类:XML和对象和String互相转化

/**
 * @description: JSON-XML转化
 * @author: GuoTong
 * @createTime: 2023-05-19 10:50
 * @since JDK 1.8 OR 11
 **/
@Slf4j
public class JSONXMLUtils {


    //XML文件头
    private static final String XML_HEAD = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";

    private static XmlMapper xmlMapper = new XmlMapper();

    public static String javaBeanToXml(Object obj) {
        String xml = null;
        if (Objects.isNull(obj)) {
            return xml;
        }
        try {
            xml = xmlMapper.writeValueAsString(obj);
        } catch (Exception e) {
            log.error("javaBeanToXml error, obj={}, xml={}", obj, xml, e);
            return xml;
        }
        // 添加xml文件头
        return XML_HEAD + xml;
    }


    public static <T> T deseralize(String str, Class<T> cls) {
        InputStream inputStream = new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8));
        T response = null;
        try {
            response = xmlMapper.readValue(inputStream, cls);
        } catch (IOException e) {
            log.error("xml反编码出错");
            e.printStackTrace();

        }
        return response;
    }

    public static <T> String serialize(T requestObj) {
        xmlMapper.enable(SerializationFeature.INDENT_OUTPUT);
        String req = null;
        try {
            req = xmlMapper.writeValueAsString(requestObj);
        } catch (JsonProcessingException e) {
            log.error("xml编码出错");
        }
        return req;

    }

效果

image

结束!!!遇到一个坑就是jackson-dataformat-xml的版本不能选太高,选2.15的有问题,退到2.14就ok

posted on 2023-05-19 12:57  白嫖老郭  阅读(1197)  评论(0编辑  收藏  举报

导航