Android Studio 使用Gson和GsonFormat

作者: Huigesi | 来源:发表于2018-05-07 22:47 被阅读1342次

    前言:

    在日常开发中,我们可能会面对很多复杂的Json数据,每次都要费点脑筋去写解析Json的代码。Json解析的方法有很多种,今天,我们来介绍如何用Gson+GsonFormat来解析Json吧。

    一、Gson与GsonFormat的导入

    Gson是Google提供的用来在Java对象和JSON数据之间进行映射的Java类库。可以将一个Json字符转成一个Java对象,或者将一个Java转化为Json字符串。

    到(Gson的GitHub)里可以看到,(在有网络的情况下)我们只需将下面这行代码放进build.gradle的dependencies下就行。

    compile 'com.google.code.gson:gson:2.8.4'

    Gson的导入:

    Gson的导入

    接下来是GsonFormat,GsonFormat可以帮你格式化Json数据,并且自动生成相应的属性类。

    Gson的导入我们到Settings/plugins/Browse repositories里导入就行了。(Mac系统的plugins在左上角的Android Studio/Preferences目录下)

    安装完成后记得点restart Android Studio重启。

    GsonFormat的导入:

    GsonFormat的导入

    如何验证安装是否成功呢?在java文件上按alt+S(苹果端按command+N再点击GsonFormat),弹出GsonFormat的窗口则代表安装成功。

    验证安装是否成功

    二、GsonFormat和Gson的使用

    首先是GsonFormat,这次我们来解析的json数据如下:

    {"date":"20180507","message":"Success !","status":200,"city":"广州","count":1642,"data":{"shidu":"86%","pm25":14.0,"pm10":24.0,"quality":"优","wendu":"26","ganmao":"各类人群可自由活动","yesterday":{"date":"06日星期日","sunrise":"05:52","high":"高温 30.0℃","low":"低温 24.0℃","sunset":"18:56","aqi":44.0,"fx":"无持续风向","fl":"<3级","type":"雷阵雨","notice":"带好雨具,别在树下躲雨"},"forecast":[{"date":"07日星期一","sunrise":"05:51","high":"高温 27.0℃","low":"低温 21.0℃","sunset":"18:57","aqi":43.0,"fx":"无持续风向","fl":"<3级","type":"大到暴雨","notice":"雨势转大,在外找好避雨处"},{"date":"08日星期二","sunrise":"05:51","high":"高温 26.0℃","low":"低温 21.0℃","sunset":"18:57","aqi":49.0,"fx":"无持续风向","fl":"<3级","type":"大到暴雨","notice":"雨势转大,在外找好避雨处"},{"date":"09日星期三","sunrise":"05:50","high":"高温 25.0℃","low":"低温 21.0℃","sunset":"18:58","aqi":57.0,"fx":"无持续风向","fl":"<3级","type":"中雨","notice":"记得随身携带雨伞哦"},{"date":"10日星期四","sunrise":"05:49","high":"高温 26.0℃","low":"低温 21.0℃","sunset":"18:58","aqi":53.0,"fx":"东南风","fl":"3-4级","type":"多云","notice":"阴晴之间,谨防紫外线侵扰"},{"date":"11日星期五","sunrise":"05:49","high":"高温 28.0℃","low":"低温 22.0℃","sunset":"18:59","aqi":45.0,"fx":"东风","fl":"3-4级","type":"阵雨","notice":"阵雨来袭,出门记得带伞"}]}}
    

    格式很乱对吧,没关系,我们把它复制到GsonFormat窗口里format一下。

    GsonFormat的格式化

    格式完成后就变成了这样:

    {
    "date": "20180507",
    "message": "Success !",
    "status": 200,
    "city": "广州",
    "count": 1642,
    "data": {
        "shidu": "86%",
        "pm25": 14,
        "pm10": 24,
        "quality": "优",
        "wendu": "26",
        "ganmao": "各类人群可自由活动",
        "yesterday": {
            "date": "06日星期日",
            "sunrise": "05:52",
            "high": "高温 30.0℃",
            "low": "低温 24.0℃",
            "sunset": "18:56",
            "aqi": 44,
            "fx": "无持续风向",
            "fl": "<3级",
            "type": "雷阵雨",
            "notice": "带好雨具,别在树下躲雨"
        },
        "forecast": [
            {
                "date": "07日星期一",
                "sunrise": "05:51",
                "high": "高温 27.0℃",
                "low": "低温 21.0℃",
                "sunset": "18:57",
                "aqi": 43,
                "fx": "无持续风向",
                "fl": "<3级",
                "type": "大到暴雨",
                "notice": "雨势转大,在外找好避雨处"
            },
            {
                "date": "08日星期二",
                "sunrise": "05:51",
                "high": "高温 26.0℃",
                "low": "低温 21.0℃",
                "sunset": "18:57",
                "aqi": 49,
                "fx": "无持续风向",
                "fl": "<3级",
                "type": "大到暴雨",
                "notice": "雨势转大,在外找好避雨处"
            },
            {
                "date": "09日星期三",
                "sunrise": "05:50",
                "high": "高温 25.0℃",
                "low": "低温 21.0℃",
                "sunset": "18:58",
                "aqi": 57,
                "fx": "无持续风向",
                "fl": "<3级",
                "type": "中雨",
                "notice": "记得随身携带雨伞哦"
            },
            {
                "date": "10日星期四",
                "sunrise": "05:49",
                "high": "高温 26.0℃",
                "low": "低温 21.0℃",
                "sunset": "18:58",
                "aqi": 53,
                "fx": "东南风",
                "fl": "3-4级",
                "type": "多云",
                "notice": "阴晴之间,谨防紫外线侵扰"
            },
            {
                "date": "11日星期五",
                "sunrise": "05:49",
                "high": "高温 28.0℃",
                "low": "低温 22.0℃",
                "sunset": "18:59",
                "aqi": 45,
                "fx": "东风",
                "fl": "3-4级",
                "type": "阵雨",
                "notice": "阵雨来袭,出门记得带伞"
            }
        ]
    }
    

    }

    这样我们看是不是更舒服点?

    GsonFormat的格式化除了帮助我们看清json数据,还可以帮助我们检查json数据格式是否正确哦。

    从格式化后的代码我们可以看到,这段json数据里的属性很多,而且有嵌套关系,如果要把这段json数据的属性类全部写出来,要费很大功夫。

    接下来就用到GsonFormat的另一个功能啦,就是帮我们生成Json数据里的属性类。

    首先我们自己新建一个类,叫WeatherBean, 然后在这个类里按alt+S打开GsonFormat,把json数据放进去,再点ok,json里的属性类就都自动生成出来啦。

    具体操作如下:

    GsonFormat的使用

    有了属性类之后,我们怎么将json数据的内容解析出来呢?

    在要求返回一个bean类型的情况下,如果是用JsonObject解析,我们要获取数据->把数据内容set到属性类里,单这两部在遇到复杂json数据时就可以让很多人头疼了。

    比如本文用到的json,用jsonObject的话可能要这样写:

    public static WeatherBean getWeatherTm(String res) throws JSONException {
        WeatherBean bean = new WeatherBean();
        WeatherBean.DataBean dataBean = new WeatherBean.DataBean();
        WeatherBean.DataBean.ForecastBean forecastBean = new WeatherBean.DataBean.ForecastBean();
        List<WeatherBean.DataBean.ForecastBean> forecastBeanList = new ArrayList<>();
    
        WeatherBean.DataBean.YesterdayBean yesterdayBean = new WeatherBean.DataBean.YesterdayBean();
        JSONObject jsonObject = new JSONObject(res);
        int jsStatus = jsonObject.getInt("status");
        bean.setStatus(jsStatus);
    
        String data = jsonObject.getString("data");
        JSONObject jsonObject1 = new JSONObject(data);
        String wendu = jsonObject1.getString("wendu");
        dataBean.setWendu(wendu);
    
        JSONObject jsonObject2 = jsonObject1.getJSONObject("yesterday");
        String high = jsonObject2.getString("high");
        yesterdayBean.setHigh(high);
    
        JSONArray jsonArray = jsonObject1.getJSONArray("forecast");
        for (int i = 0; i < jsonArray.length(); i++) {
            forecastBean.setHigh(jsonArray.getJSONObject(i).getString("high"));
            forecastBeanList.add(forecastBean);
        }
    
        dataBean.setForecast(forecastBeanList);
        dataBean.setYesterday(yesterdayBean);
        bean.setData(dataBean);
        return bean;
    }
    

    上面还只是或取单个数据,如果要求全部获取呢?

    当然这是我愚笨又夸张的写法,也许JsonObject可以有更好的写法。

    但是用Gson的话,直接跳过set的过程,上面的代码用Gson解析只需这样:

    public static WeatherBean getWeather(String res) {
    
    Gson gson =new Gson();
    
    WeatherBean wetherBean = gson.fromJson(res, WeatherBean.class);
    
    return wetherBean;
    
    }
    

    gson.fromJson()就帮你做了所有set数据的内容。还不用去苦恼嵌套时的数据获取。

    是不是很方便?

    在逻辑代码里获取数据也只要get相应的数据就行。

    获取数据

    以上就是使用Gson和GsonFormat解析复杂json数据的全部内容啦。


    相关文章

      网友评论

        本文标题:Android Studio 使用Gson和GsonFormat

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