我在Spring Boot中編寫代碼,我想將響應下載爲不應在任何項目目錄中創建的.json文件(Json文件),但它應該在飛行中從Java對象創建如何將響應作爲從Java對象創建的JSON文件下載
@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創建一個新文件a.json做到這一點/主/資源目錄我不想要的。我不想在任何directoy中創建此文件,但我仍然應該能夠下載文件
Nilendu,如果你得到一個可用的答案,接受答案是很好的方式。請仔細閱讀[當某人回答我的問題時該怎麼辦?](https://stackoverflow.com/help/someone-answers)。我知道你現在還不能在答案上投票,但接受你發佈的問題的答案只是對你的支持。所以請考慮... –