Android网络编程与json解析(天气APP)

作者: 小蜉蝣星蔚 | 来源:发表于2019-04-13 20:59 被阅读97次

    网络编程是安卓开发中必不可少的一个部分,这里会举一个天气APP的例子。

    效果如下:

    本文只讲述网络编程与json解析相关部分。定位,城市选择等其他内容可以自行查阅相关文章。


    天气APP效果图
    天气APP效果图
    天气APP效果图

    本次网络编程使用的是rxvolley,RxVolley是一个基于Volley的网络请求库;
    json数据解析使用的是Google的gson
    详细请见:
    RxVolley使用文档
    RxVolley官方项目地址github
    RxVolley缺点:1.图片加载性能一般2.对大资源下载支持不够。由于我们本文只需获取天气信息,资源小没有图片(app中的图片是自己写的逻辑相应配的)
    本文使用的接口如下:(和风天气等其他接口返回的数据大同小异不重复介绍)
    https://www.apiopen.top/weatherApi?city=湘潭
    访问后:

    访问天气接口
    使用下边的网站查看后的效果:
    在线json格式化网站 json数据查看

    这算是一个较为复杂的json数据了,我们开始用代码获取并解析,放入到APP中吧。

    使用Gsonformat生成对应的java对象

    GsonFormat是一个Android Studio中的插件,它可以大大提高我们生成Bean类时的速度

    AndroidStudio中下载Jsonformat插件1 AndroidStudio中下载Jsonformat插件2

    图二选中GsonFormat后右边会有个绿色的install按钮,我下载过了所以没显示。

    使用插件也很方便,将访问接口的结果复制到剪贴板,新建一个java类,鼠标右键选中Generate后选择GsonFormat,将返回的json数据拷贝进去点击ok即可生成对应的数据类。


    使用GsonFormat插件1.png
    使用GsonFormat插件2.png
    使用GsonFormat插件3.png

    以下GsonFormat插件自动生成的代码

    package com.lipiao.news;
    
    import java.util.List;
    
    public class WeatherBean {
    
        /**
         * code : 200
         * msg : 成功!
         * data : {"yesterday":{"date":"5日星期二","high":"高温 17℃","fx":"无持续风向","low":"低温 10℃","fl":"<![CDATA[<3级]]>","type":"晴"},"city":"成都","aqi":null,"forecast":[{"date":"6日星期三","high":"高温 15℃","fengli":"<![CDATA[<3级]]>","low":"低温 9℃","fengxiang":"无持续风向","type":"小雨"},{"date":"7日星期四","high":"高温 10℃","fengli":"<![CDATA[<3级]]>","low":"低温 7℃","fengxiang":"无持续风向","type":"小雨"},{"date":"8日星期五","high":"高温 10℃","fengli":"<![CDATA[<3级]]>","low":"低温 7℃","fengxiang":"无持续风向","type":"小雨"},{"date":"9日星期六","high":"高温 15℃","fengli":"<![CDATA[<3级]]>","low":"低温 8℃","fengxiang":"无持续风向","type":"多云"},{"date":"10日星期天","high":"高温 16℃","fengli":"<![CDATA[<3级]]>","low":"低温 9℃","fengxiang":"无持续风向","type":"多云"}],"ganmao":"天冷空气湿度大,易发生感冒,请注意适当增加衣服,加强自我防护避免感冒。","wendu":"10"}
         */
    
        private int code;
        private String msg;
        private DataBean data;
    
        public int getCode() {
            return code;
        }
    
        public void setCode(int code) {
            this.code = code;
        }
    
        public String getMsg() {
            return msg;
        }
    
        public void setMsg(String msg) {
            this.msg = msg;
        }
    
        public DataBean getData() {
            return data;
        }
    
        public void setData(DataBean data) {
            this.data = data;
        }
    
        public static class DataBean {
            /**
             * yesterday : {"date":"5日星期二","high":"高温 17℃","fx":"无持续风向","low":"低温 10℃","fl":"<![CDATA[<3级]]>","type":"晴"}
             * city : 成都
             * aqi : null
             * forecast : [{"date":"6日星期三","high":"高温 15℃","fengli":"<![CDATA[<3级]]>","low":"低温 9℃","fengxiang":"无持续风向","type":"小雨"},{"date":"7日星期四","high":"高温 10℃","fengli":"<![CDATA[<3级]]>","low":"低温 7℃","fengxiang":"无持续风向","type":"小雨"},{"date":"8日星期五","high":"高温 10℃","fengli":"<![CDATA[<3级]]>","low":"低温 7℃","fengxiang":"无持续风向","type":"小雨"},{"date":"9日星期六","high":"高温 15℃","fengli":"<![CDATA[<3级]]>","low":"低温 8℃","fengxiang":"无持续风向","type":"多云"},{"date":"10日星期天","high":"高温 16℃","fengli":"<![CDATA[<3级]]>","low":"低温 9℃","fengxiang":"无持续风向","type":"多云"}]
             * ganmao : 天冷空气湿度大,易发生感冒,请注意适当增加衣服,加强自我防护避免感冒。
             * wendu : 10
             */
    
            private YesterdayBean yesterday;
            private String city;
            private Object aqi;
            private String ganmao;
            private String wendu;
            private List<ForecastBean> forecast;
    
            public YesterdayBean getYesterday() {
                return yesterday;
            }
    
            public void setYesterday(YesterdayBean yesterday) {
                this.yesterday = yesterday;
            }
    
            public String getCity() {
                return city;
            }
    
            public void setCity(String city) {
                this.city = city;
            }
    
            public Object getAqi() {
                return aqi;
            }
    
            public void setAqi(Object aqi) {
                this.aqi = aqi;
            }
    
            public String getGanmao() {
                return ganmao;
            }
    
            public void setGanmao(String ganmao) {
                this.ganmao = ganmao;
            }
    
            public String getWendu() {
                return wendu;
            }
    
            public void setWendu(String wendu) {
                this.wendu = wendu;
            }
    
            public List<ForecastBean> getForecast() {
                return forecast;
            }
    
            public void setForecast(List<ForecastBean> forecast) {
                this.forecast = forecast;
            }
    
            public static class YesterdayBean {
                /**
                 * date : 5日星期二
                 * high : 高温 17℃
                 * fx : 无持续风向
                 * low : 低温 10℃
                 * fl : <![CDATA[<3级]]>
                 * type : 晴
                 */
    
                private String date;
                private String high;
                private String fx;
                private String low;
                private String fl;
                private String type;
    
                public String getDate() {
                    return date;
                }
    
                public void setDate(String date) {
                    this.date = date;
                }
    
                public String getHigh() {
                    return high;
                }
    
                public void setHigh(String high) {
                    this.high = high;
                }
    
                public String getFx() {
                    return fx;
                }
    
                public void setFx(String fx) {
                    this.fx = fx;
                }
    
                public String getLow() {
                    return low;
                }
    
                public void setLow(String low) {
                    this.low = low;
                }
    
                public String getFl() {
                    return fl;
                }
    
                public void setFl(String fl) {
                    this.fl = fl;
                }
    
                public String getType() {
                    return type;
                }
    
                public void setType(String type) {
                    this.type = type;
                }
            }
    
            public static class ForecastBean {
                /**
                 * date : 6日星期三
                 * high : 高温 15℃
                 * fengli : <![CDATA[<3级]]>
                 * low : 低温 9℃
                 * fengxiang : 无持续风向
                 * type : 小雨
                 */
    
                private String date;
                private String high;
                private String fengli;
                private String low;
                private String fengxiang;
                private String type;
    
                public String getDate() {
                    return date;
                }
    
                public void setDate(String date) {
                    this.date = date;
                }
    
                public String getHigh() {
                    return high;
                }
    
                public void setHigh(String high) {
                    this.high = high;
                }
    
                public String getFengli() {
                    return fengli;
                }
    
                public void setFengli(String fengli) {
                    this.fengli = fengli;
                }
    
                public String getLow() {
                    return low;
                }
    
                public void setLow(String low) {
                    this.low = low;
                }
    
                public String getFengxiang() {
                    return fengxiang;
                }
    
                public void setFengxiang(String fengxiang) {
                    this.fengxiang = fengxiang;
                }
    
                public String getType() {
                    return type;
                }
    
                public void setType(String type) {
                    this.type = type;
                }
            }
        }
    }
    

    接下来通过访问网络获取数据以及使用这个类。

    1.添加网络访问权限:
    <uses-permission android:name="android.permission.INTERNET" />
    
    2.dependencies下导包:
    implementation 'com.kymjs.rxvolley:rxvolley:1.1.4'//网络请求
    implementation 'com.google.code.gson:gson:2.8.5'//json解析
    
    2.子线程下访问接口获取并解析成对象
    private static WeatherBean weatherBean;
    private String weatherUrl = "https://www.apiopen.top/weatherApi?city=";
    //获取weatherBean
    public WeatherBean getWeatherBean() {
            return weatherBean;
        }
        //初始化weatherbean
    public void setWeatherBean(String city) {
            useWeatherApi(weatherUrl + city);
        }
    private void useWeatherApi(String weatherUrl) {
            try {
                RxVolley.get(weatherUrl, new HttpCallback() {
                    @Override
                    public void onSuccess(String t) {
                        //解析返回的JSON数据
                        handleWeatherJson(t);
                    }
                });
            }//try
            catch (Exception e) {
                //Log.d(TAG, "useApi: 错误");
            }
        }
     //解析json数据(weather)
        private void handleWeatherJson(String message) {
            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(message);
                Gson gson = new Gson();
                weatherBean = gson.fromJson(jsonObject.toString(), WeatherBean.class);
            } catch (JSONException e) {
                //Log.d(TAG, "handleWeatherJson: 错误");
            }
        }
    

    这样,访问接口返回的json数据就赋给插件自动生成java对象了,需要用的时候就可以很方便的获取数据了,这里我是写了个工具类,总之获取那个WeatherBean对象即可。想用什么数据就get什么即可。

    WeatherBean weatherBean= JsonUtil.getJsonUtil().getWeatherBean();
    //location
    weatherBean.getData().getCity();
    //advice
    weatherBean.getData().getGanmao();
    //省略
    //...
    

    APP中每日一句也是同样的方法,数据更简单,这里不再赘述。
    使用的是爱词霸的接口:
    http://open.iciba.com/dsapi/

    本来想上传至小米APP商店的,但....


    QQ截图20190413204709.png

    看来这APP还上不了台面...

    于是就上传至蒲公英了,感兴趣的同学欢迎点击下方链接下载或扫描二维码下载
    app下载地址

    APP下载二维码.png

    如果觉得文章写得还不错,点个赞呗~

    相关文章

      网友评论

        本文标题:Android网络编程与json解析(天气APP)

        本文链接:https://www.haomeiwen.com/subject/vgvrwqtx.html