首页 > 解决方案 > 将 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!");
            }
        }
    }

标签: javajsonweatherweather-api

解决方案


推荐阅读