6

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

0

2 Answers 2

6

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\"")
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks , it worked. Still i have one issue, downloaded file format is showing File type but data present inside that file is in JSON format. How to make file as .json type file while downloading
Do you mean you want the "Save as type" dropdown in your browser to say "json"? If so, you can add a Content-Disposition header and provide a filename with a .json suffix. Its then up to the browser to default the save-as-type dropdown to .json.
One other thing, you have annotated your method with application/json yet you're setting your response to application/octet-stream. You might want to make them the same.
Where to add this header "Content-Disposition" ? I tried adding this in ResponseEntity but it is not available
-1

you dont need to create a file, just convert the object to json using Gson,

Gson gson = new Gson ();
String jsonString = gson.toJson (user);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.