小编Den*_*tyo的帖子

使用桌面应用程序中的RestTemplate消费服务时出现问题

我在桌面应用程序中使用RestTemplate消费休息服务时出现问题,而在Web应用程序中使用时不会出现问题.

这是调试日志

15:30:40.448 [main] DEBUG o.s.web.client.RestTemplate - Reading [java.util.List] as "application/json" using [org.springframework.http.converter.json.MappingJacksonHttpMessageConverter@98adae2]
15:30:40.452 [main] DEBUG httpclient.wire.content - << "[{"name":"Indonesia","id":1},{"name":"AlaySia","id":2},{"name":"Autraliya","id":3}]"
Run Code Online (Sandbox Code Playgroud)

线程"main"中的异常java.lang.ClassCastException:java.util.LinkedHashMap无法强制转换为com.mgm.domain.Country

这是我使用的代码.

 String url = "http://localhost:8080/mgm/country";
    List<MediaType> mediaTypes = new ArrayList<MediaType>();
    mediaTypes.add(MediaType.APPLICATION_JSON);
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(mediaTypes);
    HttpEntity<Country> httpEntity = new HttpEntity<Country>(null, headers);
    try {
        ResponseEntity<List> responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, List.class);
        List<Country> countries = responseEntity.getBody();
        System.out.println(countries.get(0).getName());

    } catch (RestClientException exception) {
        exception.printStackTrace();
    }
Run Code Online (Sandbox Code Playgroud)

当我将它放在网络应用程序中时,上面的代码不会出错.我使用Spring Rest MVC提供JSON并将其与RestTemplate一起使用.

我认为,当杰克逊转换的问题java.util.LinkedHashMapCountry.看起来countries.get(0)实际上有LinkedHashMap类型没有Country,当我调用一个Country …

java spring spring-mvc resttemplate

5
推荐指数
1
解决办法
1万
查看次数

标签 统计

java ×1

resttemplate ×1

spring ×1

spring-mvc ×1