【问题标题】:How to download response as a JSON file created from Java Object如何将响应下载为从 Java 对象创建的 JSON 文件
【发布时间】: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


    【解决方案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\"")
    

    【讨论】:

    • 谢谢,它成功了。我仍然有一个问题,下载的文件格式显示文件类型,但该文件中存在的数据是 JSON 格式。下载时如何将文件制作为 .json 类型的文件
    • 您的意思是您希望浏览器中的“另存为类型”下拉菜单显示“json”吗?如果是这样,您可以添加 Content-Disposition 标头并提供带有 .json 后缀的文件名。然后由浏览器将另存为类型下拉菜单默认为.json。
    • 另外一件事,您已经用application/json 注释了您的方法,但您将您的响应设置为application/octet-stream。您可能希望使它们相同。
    • 在哪里添加这个标题“Content-Disposition”?我尝试在 ResponseEntity 中添加它,但它不可用
    【解决方案2】:

    您不需要创建文件,只需使用 Gson 将对象转换为 json,

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

    【讨论】:

      猜你喜欢
      • 2020-11-15
      • 2022-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-10
      • 1970-01-01
      相关资源
      最近更新 更多