Generics with Spring RESTTemplate

后端 未结 4 1849
梦毁少年i
梦毁少年i 2020-11-28 23:31

I have a class like that:

public class Wrapper {

 private String message;
 private T data;

 public String getMessage() {
    return message;
 }

          


        
相关标签:
4条回答
  • 2020-11-28 23:58

    The only thing I think you could do is creating a new class that extends Wrapper and uses model as a generic.

    class WrapperWithModel extends Wrapper<Model>{};
    
    WrapperWithModel response = restTemplate.getForObject(URL, WrapperWithModel.class);
    

    It's not the best solution, but at least you won't have to unmarshall manually the response.

    0 讨论(0)
  • 2020-11-29 00:03

    Do not use generics with RestTemplate. Wrap request and response object with wrapper object that will hide the generics.

    0 讨论(0)
  • 2020-11-29 00:03
            ResponseEntity<Result>
                    response = restTemplate.postForEntity("/user", user, Result.class);
    
            ObjectMapper objectMapper=new ObjectMapper();
            String content = objectMapper.writeValueAsString(response.getBody().getData());
            User user1 = objectMapper.readValue(content, User.class);
    
    0 讨论(0)
  • 2020-11-29 00:20

    ParameterizedTypeReference has been introduced in 3.2 M2 to workaround this issue.

    Wrapper<Model> response = restClient.exchange(loginUrl, 
                              HttpMethod.GET, 
                              null, 
                              new ParameterizedTypeReference<Wrapper<Model>>() {}).getBody();
    

    However, the postForObject/getForObject variant was not introduced.

    0 讨论(0)
提交回复
热议问题