Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue When Consume Rest Service with RestTemplate in Desktop App

I have a problem when Consume Rest Service with RestTemplate in Desktop App whereas the problem doesn't appear when i use in Web app.

This Is the Debugging logs

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}]"

Exception in thread "main" java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.mgm.domain.Country

And this is the Code that i use.

 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();
    }

Code above doesn't give errors when i place it in web app. I use Spring Rest MVC to Provide JSON and Consume it with RestTemplate.

I think there is a problem when Jackson Convert java.util.LinkedHashMap to Country . it Seems that countries.get(0) actually has LinkedHashMap type not Country and problem will appeared when i invoke one of Country methode like .getName()

like image 561
Jasoet Martohartono Avatar asked Jul 08 '11 09:07

Jasoet Martohartono


Video Answer


1 Answers

Try using an array instead:

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<Country[]> responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, Country[].class);
    Country[] countries = responseEntity.getBody();
    System.out.println(countries[0].getName());

} catch (RestClientException exception) {
    exception.printStackTrace();
}
like image 128
stoffer Avatar answered Sep 21 '22 22:09

stoffer