【发布时间】:2017-05-30 11:30:05
【问题描述】:
我正在 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 。我不想在任何目录中创建此文件,但我仍然应该能够下载该文件
【问题讨论】:
标签: java json spring-boot