Java中解析json文件

一、概述

解析本地json文件,并导出内容返回给前端

二、代码

    @ApiOperation("导入json文件")
    @PostMapping("/import")
    @DisableEncryptResponse
    public R<String> imports(@RequestParam("file") MultipartFile file) {

        File files = null;
        try {
            files = MultipartFileToFile.multipartFileToFile(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String jsonStr = "";
        try {
            FileReader fileReader = new FileReader(files);

            Reader reader = new InputStreamReader(new FileInputStream(files), "utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
//            System.out.println(jsonStr);
//            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
//            Matcher m = p.matcher(jsonStr);
//            jsonStr = m.replaceAll("");
//            System.out.println(jsonStr);
            return R.ok(jsonStr);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
package com.dbm.flowconfig.util; /**
 * Created by TongGuoBo on 2019/6/19.
 */

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @ClassName MultipartFileToFile
 * @Description MultipartFile转fie
 * @Author zhangyj
 * @Date 2023
 **/
public class MultipartFileToFile {

    /**
     * MultipartFile 转 File
     *
     * @param file
     * @throws Exception
     */
    public static File multipartFileToFile(MultipartFile file) throws Exception {

        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除本地临时文件
     * @param file
     */
    public static void delteTempFile(File file) {
    if (file != null) {
        File del = new File(file.toURI());
        del.delete();
    }
}
}

三、使用postman测试

猜你喜欢

转载自blog.csdn.net/Jiang5106/article/details/130217125