微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

android 天气预报 json解析

Android 天气预报应用是非常常见的应用。大多数天气预报应用获取数据的方式是通过 JSON API。这种方法要求我们对 JSON 数据进行解析。下面我们来介绍一下如何解析 JSON 数据。

{
    "weather":{
        "location":{
            "name":"Shanghai","region":"Shanghai","country":"China","lat":"31.22","lon":"121.46","tz_id":"Asia\/Shanghai","localtime_epoch":1576644566,"localtime":"2019-12-18 0:49"
        },"current":{
            "temp_f":50.0,"temp_c":10.0,"last_updated_epoch":1576644000,"last_updated":"2019-12-18 00:40","condition":{
                "text":"Partly cloudy","icon":"\/\/cdn.weatherapi.com\/weather\/64x64\/night\/116.png","code":1003
            },"wind_mph":9.2,"wind_kph":14.8,"wind_degree":60,"wind_dir":"ENE","pressure_mb":1020.0,"pressure_in":30.6,"precip_mm":0.0,"precip_in":0.0,"humidity":60,"cloud":75,"feelslike_c":9.8,"feelslike_f":49.6,"vis_km":10.0,"vis_miles":6.0
        }
    }
}

android 天气预报 json解析

在上面的 JSON 数据中,节点 "weather" 是一个包含两个字节点的对象。它们是 "location" 和 "current"。我们需要解析 "current" 节点中的数据。

JSONObject jsonObject = new JSONObject(jsonString);
JSONObject currentObject = jsonObject.getJSONObject("weather").getJSONObject("current");
String tempC = currentObject.getDouble("temp_c");
String conditionText = currentObject.getJSONObject("condition").getString("text");

上述代码解析了 JSON 数据,获取了 "temp_c" 和 "condition" 的信息。我们可以像下面这样显示这些信息。

String displayText = getString(R.string.temp_colon) + tempC + "°C" + 
        "\n" + getString(R.string.condition_colon) + conditionText;
textView.setText(displayText);

这样,我们就可以将获取的天气信息显示在应用中了。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐