【问题标题】:JSON to CSV API with Spring RestTemplate带有 Spring RestTemplate 的 JSON 到 CSV API
【发布时间】:2020-10-01 13:37:57
【问题描述】:

从我自己的 API 获取 JSON 后,我想将 JSON 转换为 CSV API。 JSON to CSV API 需要在 POST 请求中传递电子邮件和 JSON。现在我可以在本地存储 JSON,但是如何在请求中同时传递电子邮件和 JSON,以及如何处理响应中的 CSV?

控制器

@PostMapping("/generateExcel")
public String getEmployeeCsv(@RequestBody String email) {
        
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    
    HttpEntity<String> entity = new HttpEntity<String>(headers);
        
    String json = restTemplate.exchange("http://localhost:8080/SwaggerTest/employees", HttpMethod.GET, entity, String.class).getBody();
        
    entity = new HttpEntity<String>(json, email, headers);
        
    return restTemplate.exchange("https://json-csv.com/api/getcsv", HttpMethod.POST, entity, String.class).getBody();
}

更新: 我按照@Adrien 的建议创建了一个带有电子邮件和 json 字符串字段的 EmployeeCsvParams 类,但我仍然需要处理响应中的 CSV。

@PostMapping("/generateExcel")
    public String getEmployeeCsv(@RequestBody String email) {
        
        HttpHeaders headers  = new HttpHeaders();
        EmployeeCsvParams params = new EmployeeCsvParams();
        
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        
        HttpEntity<String> entity = new HttpEntity<String>(headers);
        
        String json = restTemplate.exchange("http://localhost:8080/SwaggerTest/employees", HttpMethod.GET, entity, String.class).getBody();
        
        params.setEmail(email);
        params.setJson(json);
        HttpEntity<EmployeeCsvParams> entity2 = new HttpEntity<EmployeeCsvParams>(params, headers);
        
        return restTemplate.exchange("https://json-csv.com/api/getcsv", HttpMethod.POST, entity2, String.class).getBody();
    }

【问题讨论】:

    标签: spring spring-boot spring-resttemplate


    【解决方案1】:

    来自spring docs @RequestBody “您可以使用@RequestBody 注解来读取请求正文并通过HttpMessageConverter 将其反序列化为一个对象。...”

    所以我假设您可以在下面创建对象并将其用作端点中的参数。

    public class EmployeeCsvParams {
    
        /* Fields */
        
        private String email;
        private String json;
    
        /* Getters and Setters */
    
        public String getEmail() { return this.email; }
        public void setEmail(String email) { this.email = email; }
    
        public String getJson() { return this.json; }
        public void setJson(String json) { this.json = json; }
    
    }
    
    @PostMapping("/generateExcel")
    public String getEmployeeCsv(@RequestBody EmployeeCsvParams employeeCsvParams) 
    {
        /* ... */ 
    } 
    

    【讨论】:

    • 感谢@Adrien!关于我应该如何处理 CSV 的任何想法,因为我确实得到了 200 OK 响应。
    猜你喜欢
    • 2016-04-11
    • 1970-01-01
    • 1970-01-01
    • 2011-12-27
    • 2018-02-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-04
    • 1970-01-01
    相关资源
    最近更新 更多