xml转json 带完整案例

说明:最近有个需求就是第三方的接口返回数据有的是json有些是xml,需要使用excel批量查询,并下载查询到数据,所有需要将xml格式都转化成json在处理(完整的domo会上传到资源)


前言

概述:
第一:讲解下xml转成json
第二:附上使用aspose的excel处理,将excel表格填充数据,上传后端,批量查询数据,并下载查询数据的excel表格
第三:此次案例小编使用springboot整合mysql,mybaits,mybatis.generator(自动生成)


提示:以下是本篇文章正文内容,下面案例可供参考

一、xml转json

1.进入依赖

 <!--版本控制-->
  <properties>
 	<jackson.version>2.11.0</jackson.version>
  <properties>
 <!--依赖-->
 <dependency>
     <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>${jackson.version}</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>${jackson.version}</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>${jackson.version}</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.dataformat</groupId>
        <artifactId>jackson-dataformat-xml</artifactId>
        <version>${jackson.version}</version>
    </dependency>

2.准备转化的xml格式和效果说明

小编设计了单个节点tree1,2个长度的数组的xml数据

在这里插入图片描述
转化成json的格式(有多个节点也是一样的处理)

{
	"dataBody":[
 		{"password":"456","bz":"学生一号","id":"2","power":"user","username":"bbb"},
 		{"password":"123","bz":"学生一号","id":"1","power":"admin","username":"aaa"} 
],
	"head":{"code":"1","success":"true","message":"success"}
}

3.定义实体类

定义俩个实体类(名字任意取)
DataRoot 封装大节点 如小编准备的xml数据里面的(ROOT/HEAD/BODY)
DataBody 封装小节点(小编数据中只有一个小节点tree1)
注明:节点名称必须和xml节点保持一致

代码如下

package sqy.xml.bean;

import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * @author suqinyi
 * @Date 2021/4/2
 * 定义大节点 ROOT,HEAD,BODY和xml文件节点对应
 */
@JacksonXmlRootElement(localName = "ROOT")
public class DataRoot implements Serializable {

    /**
     * 获取信息头
     */
    @JacksonXmlProperty(localName = "HEAD")
    public HashMap<String, Object> head = new HashMap<>();

    /**
     * 获取信息主体body
     */
    @JacksonXmlProperty(localName = "BODY")
    public ArrayList<HashMap<String, Object>> dataBody = new ArrayList();

}

package sqy.xml.bean;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * @author suqinyi
 * @Date 2021/4/2
 */
@JacksonXmlRootElement(localName = "BODY")
public class DataBody {

	//如有多个节点,自行添加
    @JacksonXmlProperty(localName = "tree1")//节点名称
    public ArrayList<HashMap<String, Object>> tree1 = new ArrayList<>();

}

4.使用jackson处理,将xml转成json

package sqy.controller;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sqy.util.responseUtil.ServiceResult;
import sqy.util.serialize.JsonUtil;
import sqy.xml.bean.DataRoot;

/**
 * @author suqinyi
 * @Date 2021/4/2
 */
@Slf4j
@RestController
@RequestMapping("/xmlToJson")
public class XmlToJsonController {

    //将xml数据转成Json
    @RequestMapping("/test02")
    public ServiceResult<?> xmlToJson() {
        //构造一个节点(tree1)的xml格式的数据
        String result = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" +
                "<ROOT>\n" +
                "    <HEAD>\n" +
                "        <success>true</success>\n" +
                "        <code>1</code>\n" +
                "        <message>success</message>\n" +
                "    </HEAD>\n" +
                "    <BODY>\n" +
                "        <tree1>\n" +
                "            <id>1</id>\n" +
                "            <username>aaa</username>\n" +
                "            <password>123</password>\n" +
                "            <bz>学生一号</bz>\n" +
                "            <power>admin</power>\n" +
                "        </tree1>\n" +
                "        <tree1>\n" +
                "            <id>2</id>\n" +
                "            <username>bbb</username>\n" +
                "            <password>456</password>\n" +
                "            <bz>学生二号</bz>\n" +
                "            <power>user</power>\n" +
                "        </tree1>\n" +
                "    </BODY>\n" +
                "</ROOT>\n" +
                "\n";
        log.info("前result{{}}", result);
        result = result.replaceAll("\\\\n", "");
        result = result.replaceAll("\\\\", "");
        //result = result.substring(1).substring(0, result.length() - 1);

        log.info("后处理result{{}}", result);
        XmlMapper mMapper = JsonUtil.getXmlMapper();
        DataRoot dataRoot = new DataRoot();
        try {
            //将xml转成json
            dataRoot = mMapper.readValue(result, new TypeReference<DataRoot>() {
            });
            log.info("JsonData{{}}", JSON.toJSONString(dataRoot));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return ServiceResult.error(e.getMessage());
        }
        return ServiceResult.success(dataRoot);
    }

}

JsonUtil.java

package sqy.util.serialize;


import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import sqy.util.staticMes.Usual;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.TimeZone;

public class JsonUtil {

    /**
     * 格式化Date,为yyyy-MM-dd HH:mm:ss格式
     */
    public final static DateFormat mfAll = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    /**
     * 格式化Date,为yyyy-MM-dd HH:mm:ss.SSS格式
     */
    public final static DateFormat mfAllMS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

    /**
     * 获取预先配置好的ObjectMapper
     *
     * @return
     */
    public static ObjectMapper getJsonMapper() {
        ObjectMapper om = new ObjectMapper();
        om.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
//        om.configure(SerializationFeature.WRITE_NULL_MAP_VALUES,false);
//        om.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS,false);

        //通过该方法对mapper对象进行设置,所有序列化的对象都将按改规则进行系列化
        //Include.Include.ALWAYS 默认
        //Include.NON_DEFAULT 属性为默认值不序列化
        //Include.NON_EMPTY 属性为 " 或者为 NULL 都不序列化
        //Include.NON_NULL 属性为NULL 不序列化
        om.setSerializationInclusion(Include.NON_NULL);
        //日期修改为String格式进行传输
        om.setDateFormat(JsonUtil.mfAllMS);
        //设置时区
        om.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        om.setLocale(Locale.CHINA);
        return om;
    }

    /**
     * 获取预先配置好的ObjectMapper
     *
     * @return
     */
    public static XmlMapper getXmlMapper() {
        XmlMapper mMapper = new XmlMapper();
        mMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        mMapper.disable(SerializationFeature.WRITE_NULL_MAP_VALUES);
        mMapper.setSerializationInclusion(Include.NON_NULL);
        mMapper.setDateFormat(Usual.mfAll);
        //设置时区
        mMapper.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        mMapper.setLocale(Locale.CHINA);
        return mMapper;
    }
}

二、使用Aspose做excel批量查询,并下载

1.小编来张图示

在这里插入图片描述
需要的话去我的上传的资源下载


完结
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐