将对象导出成为json文件


前言

需求:将复杂对象导出为一个json文件,在将json文件导入,生成对应的数据。
用于不同环境下的数据迁移,本文主要记录前半部分(将对象导出为json文件)

一、一个controller解决


import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "json/file")
public class JsonFileController {
    
    

    @GetMapping(value = "download")
    public void downLoad(HttpServletResponse response) {
    
    
        response.setContentType("text/plain");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;fileName=demo.json");

        // 制造假数据,模拟JSON数据
        List<Person> list = new ArrayList<>();
        list.add(new Person(1L, "张三", 18));
        list.add(new Person(2L, "李四", 20));
        list.add(new Person(3L, "王五", 26));

        ByteArrayInputStream is = null;
        OutputStream os = null;
        try {
    
    
            // 对象转换为字符串
//            String s = JSON.toJSONString(list);
            String s = "{\"code\":0,\"data\":\"aaaaaa\",\"msg\":\"成功\"}";
            System.out.println(s);

            is = new ByteArrayInputStream(s.getBytes());
            os = response.getOutputStream();

            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
    
    
                os.write(buffer, 0, len);
            }
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            if (os != null) {
    
    
                try {
    
    
                    os.close();
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                }
            }
            if (is != null) {
    
    
                try {
    
    
                    is.close();
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                }
            }
        }

    }
}

二、导出文件名

详见:fileName=demo.json

        response.setHeader("Content-Disposition", "attachment;fileName=demo.json");

总结

在postman中,会直接得到json文件内容
在这里插入图片描述

在浏览器上时,会直接得到一个文件

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_37700773/article/details/128455497