简体   繁体   中英

RestEntity Not Working returns empty Body

I am using spring 2.0.5 Release as Parent. I am new to Spring. And I am using this API https://www.metaweather.com/api/location/2487956/ to try and display it using Object Mapper and I am having an issue with RestTemplate.

public void read() throws IOException {
     RestTemplate rest = new RestTemplate();
     ResponseEntity<String> response  = rest.getForEntity("https://www.metaweather.com/api/location/2487956", String.class);
     ObjectMapper mapper = new ObjectMapper();
     JsonNode root = mapper.readTree(response.getBody());
     JsonNode name = root.path("weather_state_name");

     System.out.println(response.getBody());
}

Your RestEntity is fine you're not parsing your response properly. The weather_state_name is in an array named consolidated_weather. Something following will work a/c to your needs.

        ObjectMapper mapper = new ObjectMapper();
        JsonNode root = mapper.readTree(response.getBody());
        JsonNode consolidated_weather =root.get("consolidated_weather");
        consolidated_weather.forEach(x -> {

            System.out.println( x.get("weather_state_name"));
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM