Spring 引导:将响应转换为 pojo

Spring boot: Converting response to pojo

我正忙于集成测试。我很难将响应主体转换为所需的实体数据:

  HttpHeaders headers = new HttpHeaders();
        headers.add("header_name", "header_value");
        headers.setContentType(MediaType.APPLICATION_XML);
        HttpEntity<String> request = new HttpEntity<String>(fileToBeRead("file.xml"), headers);
        ResponseEntity<String> response = restTemplate.postForEntity("http://localhost:8081/api", request, String.class);

如何将收到的 json 数据转换为 Java POJO。?

只需在“post”方法中使用您的 POJO 而不是 String.class
ResponseEntity<MyPojo> response = restTemplate.postForEntity("http://localhost:8081/api", request, MyPojo.class);

或直接:
MyPojo myPojo = restTemplate.postForObject("http://localhost:8081/api", request, MyPojo.class);

如果您遵循了测试的标准 Spring 引导设置,那么 Resttemplate 会自动配置合理的默认值以反序列化您的 POJO(最有可能使用 Jackson 库)。