Reputation: 83
I am writing a code in Spring Boot where i want to download response as a .json file(Json file) which should not be created in any of my project directory but it should be created on the fly from java Object
@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();
}
}
}
I am able to do this with above code but every time i make request it creates a new file a.json in src/main/resource directory Which i don't want . i don't want to create this file in any directoy but still i should be able to download the file
Upvotes: 6
Views: 13913
Reputation: 3662
Then don't write it to a file!
byte[] buf = mapper.writeValueAsBytes(user);
return ResponseEntity
.ok()
.contentLength(buf.length)
.contentType(
MediaType.parseMediaType("application/octet-stream"))
.body(new InputStreamResource(new ByteArrayInputStream(buf)));
EDIT
To prompt browser for .json
file type add a header
.header("Content-Disposition", "attachment; filename=\"any_name.json\"")
Upvotes: 6
Reputation: 333
you dont need to create a file, just convert the object to json using Gson,
Gson gson = new Gson ();
String jsonString = gson.toJson (user);
Upvotes: -1