RestTemplate: how to get generic List response [duplicate]

怎甘沉沦 提交于 2019-12-24 00:58:28

问题


We are using restemplate in a commons package for our application. So we need to use generic types.

I read many solutions about that, but none seems to not work for us, and we constantly get (on the client side):

java.util.LinkedHashMap cannot be cast to nc.gouv.dsf.ranch.model.Pays

Here is the code (sum up):

public List<T> findAll(C criteria) {
[...]
                ResponseEntity<List<T>> response = 
                    restTemplateFactory.getRestTemplate().exchange(
                            url, 
                            HttpMethod.GET, 
                    new HttpEntity<>(createHttpHeaders(srvId)),
                    new ParameterizedTypeReference<List<T>>() {}
                            );          

            return response.getBody();
}

I though ParameterizedTypeReference what the solution to this kind of problems but its doesn't work.

PS: we are using springboot 1.3.1.RELEASE


回答1:


It seems the request is returning a Map and we are trying to cast it into list, hence the exception. Can you try the following:

ResponseEntity<Map<String, Object>> response = 
            restTemplateFactory.getRestTemplate().exchange(
                    url, 
                    HttpMethod.GET, 
            new HttpEntity<>(createHttpHeaders(srvId)),
            new ParameterizedTypeReference<Map<String, Object>>() {}
                    );


来源:https://stackoverflow.com/questions/35834296/resttemplate-how-to-get-generic-list-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!