java - 将 JSON 转换为 HashMap 时出现 NullPointerException,代码如下
问题描述
我真的很挣扎这段代码尝试不同的方法将 JSON 转换为 HashMap 但仍然没有任何关于代码的帮助将不胜感激。我已经尝试搜索问题但它仍然给了我其他异常,比如不是 JsonObject 并且已经尝试过不同的库,但 Google.gson 最适合我,如果您对此有任何修复,请告诉我...
import java.util.HashMap;
import java.net.*;
import java.io.*;
import java.util.Map;
import com.google.gson.*;
import com.google.gson.reflect.*;
public class Weather {
private static Map<String, Object> jsonToMap(String str){
Map<String, Object> map = new Gson().fromJson(
str, new TypeToken<HashMap<String, Object>>() {}.getType()
);
return map;
}
public static void main(String[] args){
String apiKey = "API not Provided";
String urlString = "http://api.openweathermap.org/data/2.5/forecast?id=1174872&APPID=" + apiKey + "&units=metric";
try{
StringBuilder result = new StringBuilder();
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null)
{
result.append(line);
}
reader.close();
System.out.println("json print: ");
System.out.println(result);
Map<String, Object> respMap = jsonToMap(result.toString());
Map<String, Object> mainMap = jsonToMap(respMap.get("main").toString());
Map<String, Object> windMap = jsonToMap(respMap.get("wind").toString());
System.out.println("Current Temperature: " + mainMap.get("temp"));
System.out.println("Current Humidity: " + mainMap.get("humidity"));
System.out.println("Current Wind : " + windMap.get("speed"));
System.out.println("Current Wind Direction : " + windMap.get("deg"));
}catch(NullPointerException e){
System.out.println("Null Pointer Exception Occurred!");
}catch (IOException e)
{
System.out.println("Input Output Exception Occurred!");
}
}
}
解决方案
推荐阅读
- javascript - VS Code 编辑器击穿 .click() 函数文本 #jQuery
- node.js - 如何仅使用 multerS3 将文件类型限制为图像?
- python - 在 Python 中没有错误的中断循环 - Selenium
- reactjs - 使用反应钩子在上下文提供者中添加多个状态
- haskell - 如何防止某些值(或状态)在线程之间共享?
- yarnpkg - 如何创建一个底层链?
- python - Python 类和 __init___ 构造函数,如何创建一个列表变量?
- flutter - 在使用提供程序包的消费者中,如何将图像设置为 Flutter 中的每个构建?
- python - 每 10 行拆分/划分数据帧
- javascript - 在 Javascript 中创建计数器数组(反应原生)