1

从我自己的 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 的建议创建了一个EmployeeCsvParams包含电子邮件和 json 字符串字段的类,但我仍然需要处理响应中的 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();
    }
4

1 回答 1

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) 
{
    /* ... */ 
} 
于 2020-10-01T14:00:32.947 回答