如何将响应作为从Java对象创建的JSON文件下载

问题描述:

我在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中创建此文件,但我仍然应该能够下载文件

+0

Nilendu,如果你得到一个可用的答案,接受答案是很好的方式。请仔细阅读[当某人回答我的问题时该怎么办?](https://*.com/help/someone-answers)。我知道你现在还不能在答案上投票,但接受你发布的问题的答案只是对你的支持。所以请考虑... –

然后不要将它写入文件!

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\"") 
+0

谢谢,它的工作。我仍然有一个问题,下载的文件格式显示文件类型,但该文件内存在的数据是JSON格式。如何在下载时将文件制作为.json类型文件 –

+0

您的意思是您希望浏览器中的“保存类型”下拉菜单中显示“json”?如果是这样,您可以添加一个Content-Disposition标题并提供一个带有.json后缀的文件名。然后直到浏览器默认保存类型下拉菜单为'.json'。 – TedTrippin

+0

另一件事是,你用'application/json'注释了你的方法,但是你正在设置你对'application/octet-stream'的响应。你可能想让它们一样。 – TedTrippin

你不需要创建一个文件,只是用GSON将对象转换为JSON,

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