首页前端开发其他前端知识android 天气预报 json解析

android 天气预报 json解析

时间2023-10-21 22:46:03发布访客分类其他前端知识浏览673
导读:Android 天气预报应用是非常常见的应用。大多数天气预报应用获取数据的方式是通过 JSON API。这种方法要求我们对 JSON 数据进行解析。下面我们来介绍一下如何解析 JSON 数据。{ "weather":{...

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        }
    }
}
    

在上面的 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);
    

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

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: android 天气预报 json解析
本文地址: https://pptw.com/jishu/505045.html
ajax传递json数据格式 9200 json

游客 回复需填写必要信息