java - 我无法从 JSON 中获取字段
问题描述
我有一个方法看起来像:
@RequestMapping(value = "/weather")
public void printWeather() throws JsonProcessingException {
String url = mineApiURLwithKey;
String json = restTemplate.getForObject(url, String.class);
ObjectMapper mapper = new ObjectMapper();
String temperature = mapper.readTree(json).get("sunset").asText();
}
JSON 看起来像:
{
"coord": {
"lon": 19.7497,
"lat": 53.5043
},
"weather": [
{
"id": 500,
"main": "Rain",
"description": "light rain",
"icon": "10n"
}
],
"base": "stations",
"main": {
"temp": 280.67,
"feels_like": 279.66,
"temp_min": 279.82,
"temp_max": 281.48,
"pressure": 1010,
"humidity": 72
},
"visibility": 10000,
"wind": {
"speed": 1.79,
"deg": 325,
"gust": 3.13
},
"rain": {
"1h": 0.42
},
"clouds": {
"all": 72
},
"dt": 1619039826,
"sys": {
"type": 3,
"id": 2007860,
"country": "PL",
"sunrise": 1618975636,
"sunset": 1619027504
},
"timezone": 7200,
"id": 3093028,
"name": "Lubawa",
"cod": 200
}
但我有一个例外作为回报:
java.lang.NullPointerException:无法调用“com.fasterxml.jackson.databind.JsonNode.asText()”,因为“com.fasterxml.jackson.databind.JsonNode.get(String)”的返回值为 null
解决方案
推荐阅读
- python - 有效计算邻居之间的距离
- twig - Sublime Text 默认 HTML 注释
- reactjs - 监控 Twilio 语音通话状态
- android-studio - 无法解决:com.google.android.gms:play-services:15.0.1
- firebase - Firestore:词法或预处理器问题
- c++ - 从字符串 C++ 中删除元音
- c# - 将数组从 C++(非托管代码)检索到 C Sharp 形式(托管)
- python - 带有 .nii.gz 文件的医学成像 (PyRadiomics)
- python - 在python中使用可变数量的所需填充参数格式化字符串
- java - 如何通过反射获取函数对象的类型参数?