1

我正在创建一个应用程序,它将使用 OpenWeatherMap.org api 告诉一个城市的天气状况。在这个应用程序中,我让用户写一个城市名称,数据将从网络上获取。但是如果用户输入了错误的城市怎么办。

例如,如果用户输入 Lomdon 而不是 London。

在那种情况下我该怎么办。我使用的 Api 是“ http://api.openweathermap.org/data/2.5/weather?q=”+城市名称

提前感谢您的帮助,我是android开发的新手。

4

1 回答 1

0

如果城市不正确,您的 API 会返回错误消息。您可以像这样检查它:

http://api.openweathermap.org/data/2.5/weather?q=Lomdon

    try {
        String msg = jsonObject.getString("message");
        if (msg.equalsIgnoreCase("Error: Not found city")) {
            Log.e("TAG", "City not found");
        } else {
            // Use the data
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

我没有使用cod看起来像返回码的原因是,如果找到城市cod是一个 int,如果没有找到它是一个字符串。像这样设计 JSON 有点误导。

于 2014-11-16T12:44:23.157 回答