将对象导出成为json文件-创新互联

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

超过十年行业经验,技术领先,服务至上的经营模式,全靠网络和口碑获得客户,为自己降低成本,也就是为客户降低成本。到目前业务范围包括了:网站建设、成都网站设计,成都网站推广,成都网站优化,整体网络托管,小程序定制开发,微信开发,成都App定制开发,同时也可以让客户的网站和网络营销和我们一样获得订单和生意!
前言 需求:将复杂对象导出为一个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数据
        Listlist = 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文件内容
在这里插入图片描述

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

在这里插入图片描述

你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧


名称栏目:将对象导出成为json文件-创新互联
网站路径:http://ybzwz.com/article/ijsis.html