json - 需要使用 Spring Boot 从 OpenWeather json 获取温度
问题描述
我已经编写了 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
解决方案
只需创建一个包含代表接收到的 JSON 的嵌套类的类。
OpenWeatherResponse.class
public class OpenWeatherResponse {
private Main main;
// constructor and getters ommitted
}
主类
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();
这是最简单的方法。
您也可以编写自定义序列化程序,但这需要更多的努力。
推荐阅读
- php - 寻找逻辑来扫描阵列以寻找下一个活动时隙
- docker - docker rabbit mq 图像无法加载
- ruby-on-rails - rails 和 rake 有什么区别?
- google-cloud-platform - 具有写入权限和预定义元数据的 GCP 存储 file.getSignedUrl
- javascript - 我想用 rxjs 查找字符串序列
- python - 运行 Windows 批处理文件以使用我的 anaconda 环境调用 python 脚本
- java - 如何通过 Spring WebClient 通过服务名称从另一个微服务调用一个微服务:Java、Spring
- typescript - 使用 mongoose 文档扩展现有接口
- amazon-web-services - 在 aws 负载均衡器上托管 Pritunl VPN
- r - 根据R中的站点距离制作权重列