RestEntity Not Working 返回空的正文

我使用 spring 2.0.5 Release 作为父级。我是春天的新手。我正在使用此 API https://www.metaweather.com/api/location/2487956/尝试使用对象映射器显示它,但我遇到了 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());

}


狐的传说
浏览 113回答 1
1回答

喵喔喔

您的 RestEntity 很好,您没有正确解析您的响应。weather_state_name 位于一个名为solidated_weather 的数组中。以下内容将满足您的需求。&nbsp; &nbsp; &nbsp; &nbsp; ObjectMapper mapper = new ObjectMapper();&nbsp; &nbsp; &nbsp; &nbsp; JsonNode root = mapper.readTree(response.getBody());&nbsp; &nbsp; &nbsp; &nbsp; JsonNode consolidated_weather =root.get("consolidated_weather");&nbsp; &nbsp; &nbsp; &nbsp; consolidated_weather.forEach(x -> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println( x.get("weather_state_name"));&nbsp; &nbsp; &nbsp; &nbsp; });
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java