我正在Spring Boot中编写一个代码,我希望将响应下载为.json文件(Json文件),该文件不应该在我的任何项目目录中创建,但应该从java对象中快速创建
@RequestMapping(value = "/", method = RequestMethod.GET,produces = "application/json")
public ResponseEntity<InputStreamResource> downloadPDFFile()
throws IOException {
User user = new User();
user.setName("Nilendu");
user.setDesignation("Software Engineer");
createJsonFile(user);
ClassPathResource jsonFile = new ClassPathResource("a.json");
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
return ResponseEntity
.ok()
.contentLength(jsonFile.contentLength())
.contentType(
MediaType.parseMediaType("application/octet-stream"))
.body(new InputStreamResource(jsonFile.getInputStream()));
}
void createJsonFile(User user) {
ObjectMapper mapper = new ObjectMapper();
try {
// Convert object to JSON string and save into a file directly
File file = new File("src/main/resources/a.json");
System.out.println(file.exists()+" ++++");
mapper.writeValue(file, user);
System.out.println("File Created");
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
我可以使用上面的代码执行此操作,但每次我发出请求时,它会在src / main / resource目录中创建一个我不想要的新文件a.json。我不想在任何directoy中创建此文件,但我仍然可以下载文件
答案 0 :(得分:1)
然后不要把它写到文件中!
byte[] buf = mapper.writeValueAsBytes(user);
return ResponseEntity
.ok()
.contentLength(buf.length)
.contentType(
MediaType.parseMediaType("application/octet-stream"))
.body(new InputStreamResource(new ByteArrayInputStream(buf)));
修改
要提示.json
文件类型的浏览器添加标题
.header("Content-Disposition", "attachment; filename=\"any_name.json\"")
答案 1 :(得分:-1)
你不需要创建文件,只需使用Gson将对象转换为json,
Gson gson = new Gson ();
String jsonString = gson.toJson (user);