Java导入导出json

1.导入依赖

            <dependency>
                <groupId>commons-io</groupId>
                <artifactId>commons-io</artifactId>
                <version>2.8.0</version>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.2.70</version>
            </dependency>

2.新建Json工具类

package com.njcdv.system.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
/**
 * @Description: Json工具类
 * @Authoer:RenPL
 * @CreateDate:2022-11-15 11:09
 * @Version: 1.0.0
 */
public class JsonUtil {

    public static Map<String, String> readJson(MultipartFile multipartFile) {
        Map<String, String> result = new HashMap<>();
        try {
            String fileName = multipartFile.getOriginalFilename();
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            //MultipartFile to string
            File file = new File("/" + fileName);
            FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file);
            String jsonString = FileUtils.readFileToString(file, "UTF-8");

            if (".json".equals(suffixName) || ".txt".equals(suffixName)) {
                result.put("result", jsonString);
                result.put("code", "200");
                result.put("message", "上传成功!");
            } else {
                result.put("result", "");
                result.put("code", "500");
                result.put("message", "请上传正确格式的.json或.txt文件!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("result", "");
            result.put("code", "500");
            result.put("message", e.getMessage());
        }
        return result;
    }

    public static void exportJson(HttpServletResponse response, Object obj, String fileName){
        try {
            String jsonString = JSON.toJSONString(obj,
                    SerializerFeature.PrettyFormat,
                    SerializerFeature.WriteMapNullValue,
                    SerializerFeature.WriteDateUseDateFormat);

            String fullPath = "/" + fileName;
            File file = new File(fullPath);

            Writer write = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);
            write.write(jsonString);
            write.flush();
            write.close();

            FileInputStream fis = new FileInputStream(file);
            // force-download
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));
            response.setCharacterEncoding("utf-8");

            OutputStream os = response.getOutputStream();
            byte[] buf = new byte[1024];
            int len = 0;
            while((len = fis.read(buf)) != -1) {
                os.write(buf, 0, len);
            }
            fis.close();
            os.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

3.Controller控制层

        3.1导出json数据

    @PostMapping("/export")
    public void exportJson(HttpServletResponse response, SysEnum sysEnum) {
        //查询数据
        List<SysEnum> sysEnumList = enumService.exportEnum(sysEnum);
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateNowStr = sdf.format(date);
        //调用json工具类导出数据
        JsonUtil.exportJson(response, sysEnumList,  dateNowStr+"-enumModel.json");
    }

        3.2导入json数据

    @PostMapping("/import")
    public Object importJson(MultipartFile multipartFile) {
        final Map<String, String> result = JsonUtil.readJson(multipartFile);
        if ("200".equals(result.get("code"))) {
            final String jsonString = result.get("result");
            //json字符串转为json对象
            JSONArray jsonArray = JSONArray.parseArray(jsonString);
            //循环遍历json对象转为实体类对象
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                SysEnum sysEnum = JSONObject.parseObject(jsonObject.toJSONString(),SysEnum.class);
                //每次循环导入一条数据
                enumService.insertSysEnum(sysEnum);
            }
        }
        return result;
    }


版权声明:本文为weixin_60457220原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。