首页 > 解决方案 > 无法从 API 响应中获取特定参数

问题描述

我正在尝试制作一个简单的天气应用程序。我正在使用这个API。在同一页面上是 JSON 响应中的参数列表。我可以搜索除“天气”参数之外的所有参数并得到响应。每次我尝试得到一个

java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 3 path $[0]

错误。我不确定是什么原因造成的。这是我的代码。

public class Weather {

private String city;
private OWM owm = new OWM("8984d739fa91d7031fff0e84a3d2c520");
private CurrentWeather currentWeather;
private String weather;
private Clouds cloud;

public Weather() throws APIException {
    String API_KEY = "8984d739fa91d7031fff0e84a3d2c520";
    String Location = "Brooklyn";
    String urlString = "http://api.openweathermap.org/data/2.5/weather?q=" + Location
            + "&appid=" + API_KEY + "&units=imperial";

    try {
        StringBuilder result = new StringBuilder();
        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = rd.readLine()) != null){
            result.append(line);
        }
        rd.close();
        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());
        Map<String, Object> cloudsMap = jsonToMap(respMap.get("weather").toString());
// error is  here
        System.out.println("Current Temperature: " + mainMap.get("temp"));
        System.out.println("current humidity " + mainMap.get("humidity"));
        System.out.println("clouds " + respMap.get("description"));
      //  System.out.println("weather conditions: " + cloudsMap.get("main"));
// this always returns null 
        System.out.println("wind speeds " + windMap.get("speed"));
        System.out.println("wind angle: " + windMap.get("deg"));
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
public static Map<String, Object> jsonToMap(String str){
    Map<String, Object> map = new Gson().fromJson(
           str, new TypeToken<HashMap<String, Object>>() {}.getType()
    );
    return map;
}

public String getCityName() {
    return cityName;
}
public int getCurrentWeather() throws APIException {
    owm.setUnit(OWM.Unit.IMPERIAL);
    currentWeather = owm.currentWeatherByCityName(this.cityName);
    return (int) Math.round(currentWeather.getMainData().getTemp());
}
public void setCityName(String cityName) {
    this.cityName = cityName;
}

public void setZipCode(String zipCode){
    this.zipCode = zipCode;
}
public String getZipCode(){
    return this.zipCode;
}
public String getWeather(){
    return this.weather;
}
}

我不太确定为什么那个参数不起作用。我可以搜索其他任何东西,为什么我不能搜索天气参数?

编辑:我在我的 try/catch 语句中这样做。它给了我一个NullPointerException

URL url = new URL(urlString);
            URLConnection conn = url.openConnection();
            conn.connect();

            JsonParser jp = new JsonParser();
            JsonElement root = jp.parse(new InputStreamReader((InputStream) conn.getContent()));
            JsonObject rootObj = root.getAsJsonObject();
            String description = rootObj.get("weather").getAsString();
// name of the array in the json
            System.out.println(description);

标签: javajsonapinullpointerexception

解决方案


Map<String, Object> cloudsMap = jsonToMap(respMap.get("weather").toString());

这就是问题。您正在尝试weather将响应的属性解析为对象(映射),但它实际上是一个数组。


推荐阅读