我已经编写了java spring boot应用程序来从openweatherapi获取温度。我正在获取完整的json代码,因此我只需要温度值。
如何解析和获取。
具有ResponseEntity响应的SpringBoot应用程序
@PostMapping("temperature")
ResponseEntity<?> getTemperaturebyLocationCoordinates(@ModelAttribute TemperatureBean tempBean) {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Object> response = restTemplate
.getForEntity("https://api.openweathermap.org/data/2.5/weather?lat=" + tempBean.getLatitude() + "&lon="
+ tempBean.getLongitude() + "&APPID=" + apikey + "&units=metric", Object.class);
return response;
}
{
"coord": {
"lon": 80.14,
"lat": 13.36
},
"weather": [
{
"id": 500,
"main": "Rain",
"description": "light rain",
"icon": "10n"
}
],
"base": "stations",
"main": {
"temp": 31,
"pressure": 1005,
"humidity": 70,
"temp_min": 31,
"temp_max": 31
},
"visibility": 4000,
"wind": {
"speed": 4.1,
"deg": 300
},
"clouds": {
"all": 75
},
"dt": 1565012771,
"sys": {
"type": 1,
"id": 9218,
"message": 0.0132,
"country": "IN",
"sunrise": 1564964708,
"sunset": 1565010350
},
"timezone": 19800,
"id": 1259290,
"name": "Puduvayal",
"cod": 200
}
我只想要温度:31
答案 0 :(得分:0)
只需创建一个包含嵌套类的类,即可代表接收到的JSON。
OpenWeatherResponse.class
public class OpenWeatherResponse {
private Main main;
// constructor and getters ommitted
}
Main.class
public class Main {
private int temp;
// constructor and getters ommitted
}
然后在其余调用中替换实体
final String url = "https://api.openweathermap.org/data/2.5/weather?lat=" + tempBean.getLatitude() + "&lon="
+ tempBean.getLongitude() + "&APPID=" + apikey + "&units=metric";
ResponseEntity<OpenWeatherResponse> response = restTemplate
.getForEntity(url, OpenWeatherResponse.class);
final int temp = response.getBody().getMain().getTemp();
这是最简单的方法。
您还可以编写自定义序列化程序,但这需要更多的精力。