Java导出格式化json文件

Java导出格式化json文件

直接上代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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);
}
}
}