【问题标题】:Spring RestTemplate get generic objectSpring RestTemplate 获取通用对象
【发布时间】:2016-07-20 06:52:36
【问题描述】:

我给了这个模型

public class ResponseMessage<T> {

    private T result;
    private ResultCode resultCode;
    private String details;

    public ResponseMessage(T result, ResultCode resultCode, String details) {
        this.result = result;
        this.resultCode = resultCode;
        this.details = details;
    }
//getters and setters

当我从服务器获得这个模型时,我会对其进行转换

RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject(lkAuthListUrl, String.class);
        Type listType = new TypeToken<ResponseMessage<LkAuth[]>>() {
        }.getType();
        ResponseMessage<LkAuth[]> model = Converter.me().getModel(result, listType);

在转换器中我做到了

public <T> T getModel(String jsonStr, Type type) {
        T t = null;
        try {
            t = gson.fromJson(jsonStr, type);
        } catch (Exception e) {
            System.out.print(e);
        }
        return t;
    }

我可以避免在我的方法中转换并将此职责转移到RestTemplate吗?

这有什么问题

ResponseMessage<LkAuth[]> model = restTemplate.getForObject(lkAuthListUrl, ResponseMessage<LkAuth[]>.class);

【问题讨论】:

    标签: spring generics resttemplate


    【解决方案1】:

    这可以通过在 restTemplate 对象中使用 exchange() 方法来避免,但需要进行一些更改,例如将您的数组转换为 List 并将类型作为参数的 ParameterizedTypeReference 传递(这是必要的,因为类型擦除)。其余部分与您的预期相似:

    ResponseEntity<List<LkAuth>> response =
            restTemplate.exchange(lkAuthListUrl,
                        HttpMethod.GET, null, new ParameterizedTypeReference<List<LkAuth>>() {});
    List<LkAuth> model = response.getBody();
    

    【讨论】:

      猜你喜欢
      • 2021-08-10
      • 2021-11-07
      • 2018-09-19
      • 1970-01-01
      • 2019-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多