Loading

Java导出格式化后的JSON文件

Java导出格式化json文件

直接上代码:

private void downloadJsonFile(LifeDTO lifeDTO, HttpServletResponse response) {
    String content = JSON.toJSONString(lifeDTO, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue,
            SerializerFeature.WriteDateUseDateFormat);
    BufferedOutputStream buff = null;
    ServletOutputStream outputStream = null;
    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json");
    response.setHeader("Content-Disposition", "attachment;filename=data.json");
    try {
        outputStream = response.getOutputStream();
        buff = new BufferedOutputStream(outputStream);
        buff.write(content.getBytes(StandardCharsets.UTF_8));
        buff.flush();
        buff.close();
    }catch (Exception e) {
        log.error("downloadJsonFile error", e);
    }finally {
        try {
            if (buff != null) {
                buff.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        }catch (Exception e) {
            log.error("io close error", e);
        }
    }
}
posted @ 2023-07-15 11:15  键盘侠_23  阅读(207)  评论(0)    收藏  举报