精华内容
下载资源
问答
  • 下面小编就为大家带来一篇Android利用Gson解析嵌套多层Json的简单方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
  • 使用Gson(https://github.com/google/gson)去解析json应该是很常见的,大部分的情况下我们只要创建一个Gson对象,然后根据json和对应的Java类去解析就可以了。但是对于比较复杂的json,比如下面这种,attributes...
  • Gson解析复杂json数据

    热门讨论 2011-06-21 18:07:18
    Gson解析复杂json数据,复杂的json数据用gson工具解析
  • Gson解析
  • 利用Gson解析多层嵌套的JSON数据

    万次阅读 2016-04-10 23:21:25
    数据实例:{ "error": 0, "status": "success", "results": [ { "currentCity": "青岛", "index": [ { "title": "穿衣",

    数据实例:

    {
        "error": 0,
        "status": "success",
        "results": [
            {
                "currentCity": "青岛",
                "index": [
                    {
                        "title": "穿衣",
                        "zs": "较冷",
                        "tipt": "穿衣指数",
                        "des": "建议着厚外套加毛衣等服装。年老体弱者宜着大衣、呢外套加羊毛衫。"
                    },
                    {
                        "title": "紫外线强度",
                        "zs": "中等",
                        "tipt": "紫外线强度指数",
                        "des": "属中等强度紫外线辐射天气,外出时建议涂擦SPF高于15、PA+的防晒护肤品,戴帽子、太阳镜。"
                    }
                ]
    
            }
        ]
    }
    

    代码如下:

    package com.iteam.test;
    
    import com.google.gson.Gson;
    import com.iteam.where.bean.JsonBean;
    
    public class BmobTest {
    
        public static void main(String[] args) {
    
            String s = "{\"error\":0,\"status\":\"success\",\"results\":[{\"currentCity\":\"青岛\",\"index\":[{\"title\":\"穿衣\",\"zs\":\"较冷\",\"tipt\":\"穿衣指数\",\"des\":\"建议着厚外套加毛衣等服装。年老体弱者宜着大衣、呢外套加羊毛衫。\"},{\"title\":\"紫外线强度\",\"zs\":\"最弱\",\"tipt\":\"紫外线强度指数\",\"des\":\"属弱紫外线辐射天气,无需特别防护。若长期在户外,建议涂擦SPF在8-12之间的防晒护肤品。\"}]}]}";    
            Gson gson = new Gson();    
            //把JSON数据转化为对象
            JsonBean jsonBean = gson.fromJson(s, JsonBean.class);
    
        }
    }
    

    按照JSON数据来写的bean文件:

    package com.iteam.where.bean;
    
    import java.util.List;
    
    public class JsonBean {
    
    private int error;
    private String status;
    private List<Results> results;
    public int getError() {
        return error;
    }
    public void setError(int error) {
        this.error = error;
    }
    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
    public List<Results> getResults() {
        return results;
    }
    public void setResults(List<Results> results) {
        this.results = results;
    }
    }
    
    
    
    import java.util.List;
    
    public class Results {
    
    private String currentCity;
    private List<Index> index;
    public String getCurrentCity() {
        return currentCity;
    }
    public void setCurrentCity(String currentCity) {
        this.currentCity = currentCity;
    }
    public List<Index> getIndex() {
        return index;
    }
    public void setIndex(List<Index> index) {
        this.index = index;
    }
    
    }
    
    
    
    public class Index {
    
    private String title;
    private String zs;
    private String tipt;
    private String des;
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getZs() {
        return zs;
    }
    public void setZs(String zs) {
        this.zs = zs;
    }
    public String getTipt() {
        return tipt;
    }
    public void setTipt(String tipt) {
        this.tipt = tipt;
    }
    public String getDes() {
        return des;
    }
    public void setDes(String des) {
        this.des = des;
    }
    
    }
    
    展开全文
  • Gson解析复杂Json数据

    千次阅读 2018-10-09 11:09:47
    使用Gson解析复杂的JSON数据 首先建立依赖 implementation'com.google.code.gson:gson:2.8.0' 然后根据api获取到的json数据 { &quot;status&quot;: &quot;1&quot;, &quot;info&...

    看一下大神的 文章:
    使用Gson解析复杂的JSON数据
    首先建立依赖

        implementation'com.google.code.gson:gson:2.8.0'
    

    然后根据api获取到的json数据

    {
      "status": "1",
      "info": "OK",
      "infocode": "10000",
      "count": "1",
      "geocodes": [
        {
          "formatted_address": "广东省深圳市福田区深圳会展中心",
          "province": "广东省",
          "citycode": "0755",
          "city": "深圳市",
          "district": "福田区",
          "township": [
            
          ],
          "neighborhood": {
            "name": [
              
            ],
            "type": [
              
            ]
          },
          "building": {
            "name": [
              
            ],
            "type": [
              
            ]
          },
          "adcode": "440304",
          "street": [
            
          ],
          "number": [
            
          ],
          "location": "114.059812,22.530777",
          "level": "兴趣点"
        }
      ]
    }
    

    这数据一层套一层,看着眼花缭乱,不直观,这里借用
    JSON在线视图查看器
    把JSON数据贴上去后,点击视图,展开
    在这里插入图片描述
    这就很直观看出来结构了,现在要取出的是location。我们看到,整个JSON数据中,含有5个一级子项,其中一个子项是一个数组geocodes,这个一级子项数组中只有一个元素{},序号为0,里面包含了一大堆子项,某些子项还是数组,但是刚好location不是数组,它就相当于被JSON层,geocodes层,0层这三个层包围,像剥洋葱那样一层一层地剥开就好啦。
    建立javabean 类:
    用GsonFormat插件来完成生成
    Location.java

    public class Location {
    
    
        /**
         * status : 1
         * info : OK
         * infocode : 10000
         * count : 1
         * geocodes : [{"formatted_address":"广东省深圳市福田区深圳会展中心","province":"广东省","citycode":"0755","city":"深圳市","district":"福田区","township":[],"neighborhood":{"name":[],"type":[]},"building":{"name":[],"type":[]},"adcode":"440304","street":[],"number":[],"location":"114.059812,22.530777","level":"兴趣点"}]
         */
    
        private String status;
        private String info;
        private String infocode;
        private String count;
        private List<GeocodesBean> geocodes;
    
        public String getStatus() {
            return status;
        }
    
        public void setStatus(String status) {
            this.status = status;
        }
    
        public String getInfo() {
            return info;
        }
    
        public void setInfo(String info) {
            this.info = info;
        }
    
        public String getInfocode() {
            return infocode;
        }
    
        public void setInfocode(String infocode) {
            this.infocode = infocode;
        }
    
        public String getCount() {
            return count;
        }
    
        public void setCount(String count) {
            this.count = count;
        }
    
        public List<GeocodesBean> getGeocodes() {
            return geocodes;
        }
    
        public void setGeocodes(List<GeocodesBean> geocodes) {
            this.geocodes = geocodes;
        }
    
        public static class GeocodesBean {
            /**
             * formatted_address : 广东省深圳市福田区深圳会展中心
             * province : 广东省
             * citycode : 0755
             * city : 深圳市
             * district : 福田区
             * township : []
             * neighborhood : {"name":[],"type":[]}
             * building : {"name":[],"type":[]}
             * adcode : 440304
             * street : []
             * number : []
             * location : 114.059812,22.530777
             * level : 兴趣点
             */
    
            private String formatted_address;
            private String province;
            private String citycode;
            private String city;
            private String district;
            private NeighborhoodBean neighborhood;
            private BuildingBean building;
            private String adcode;
            private String location;
            private String level;
            private List<?> township;
            private List<?> street;
            private List<?> number;
    
            public String getFormatted_address() {
                return formatted_address;
            }
    
            public void setFormatted_address(String formatted_address) {
                this.formatted_address = formatted_address;
            }
    
            public String getProvince() {
                return province;
            }
    
            public void setProvince(String province) {
                this.province = province;
            }
    
            public String getCitycode() {
                return citycode;
            }
    
            public void setCitycode(String citycode) {
                this.citycode = citycode;
            }
    
            public String getCity() {
                return city;
            }
    
            public void setCity(String city) {
                this.city = city;
            }
    
            public String getDistrict() {
                return district;
            }
    
            public void setDistrict(String district) {
                this.district = district;
            }
    
            public NeighborhoodBean getNeighborhood() {
                return neighborhood;
            }
    
            public void setNeighborhood(NeighborhoodBean neighborhood) {
                this.neighborhood = neighborhood;
            }
    
            public BuildingBean getBuilding() {
                return building;
            }
    
            public void setBuilding(BuildingBean building) {
                this.building = building;
            }
    
            public String getAdcode() {
                return adcode;
            }
    
            public void setAdcode(String adcode) {
                this.adcode = adcode;
            }
    
            public String getLocation() {
                return location;
            }
    
            public void setLocation(String location) {
                this.location = location;
            }
    
            public String getLevel() {
                return level;
            }
    
            public void setLevel(String level) {
                this.level = level;
            }
    
            public List<?> getTownship() {
                return township;
            }
    
            public void setTownship(List<?> township) {
                this.township = township;
            }
    
            public List<?> getStreet() {
                return street;
            }
    
            public void setStreet(List<?> street) {
                this.street = street;
            }
    
            public List<?> getNumber() {
                return number;
            }
    
            public void setNumber(List<?> number) {
                this.number = number;
            }
    
            public static class NeighborhoodBean {
                private List<?> name;
                private List<?> type;
    
                public List<?> getName() {
                    return name;
                }
    
                public void setName(List<?> name) {
                    this.name = name;
                }
    
                public List<?> getType() {
                    return type;
                }
    
                public void setType(List<?> type) {
                    this.type = type;
                }
            }
    
            public static class BuildingBean {
                private List<?> name;
                private List<?> type;
    
                public List<?> getName() {
                    return name;
                }
    
                public void setName(List<?> name) {
                    this.name = name;
                }
    
                public List<?> getType() {
                    return type;
                }
    
                public void setType(List<?> type) {
                    this.type = type;
                }
            }
        }
    }
    
    

    我们看到,需要的location数据被包含在了Location类中的类GeocodesBean里了,建议把GeocodesBean类直接剪切掉,新建一个GeocodesBean类贴进去,把类头的static删掉。最好不要把我们要的数据放在类中类。
    即修改后的
    Location.java

    public class Location {
    
    
        /**
         * status : 1
         * info : OK
         * infocode : 10000
         * count : 1
         * geocodes : [{"formatted_address":"广东省深圳市坪山区六角大楼","province":"广东省","citycode":"0755","city":"深圳市","district":"坪山区","township":[],"neighborhood":{"name":[],"type":[]},"building":{"name":[],"type":[]},"adcode":"440310","street":[],"number":[],"location":"114.360910,22.678323","level":"兴趣点"}]
         */
    
        private String status;
        private String info;
        private String infocode;
        private String count;
        private List<GeocodesBean> geocodes;
    
        public String getStatus() {
            return status;
        }
    
        public void setStatus(String status) {
            this.status = status;
        }
    
        public String getInfo() {
            return info;
        }
    
        public void setInfo(String info) {
            this.info = info;
        }
    
        public String getInfocode() {
            return infocode;
        }
    
        public void setInfocode(String infocode) {
            this.infocode = infocode;
        }
    
        public String getCount() {
            return count;
        }
    
        public void setCount(String count) {
            this.count = count;
        }
    
        public List<GeocodesBean> getGeocodes() {
            return geocodes;
        }
    
        public void setGeocodes(List<GeocodesBean> geocodes) {
            this.geocodes = geocodes;
        }
    
    
    }
    
    

    GeocodesBean.java

    public class GeocodesBean {
            /**
             * formatted_address : 广东省深圳市坪山区六角大楼
             * province : 广东省
             * citycode : 0755
             * city : 深圳市
             * district : 坪山区
             * township : []
             * neighborhood : {"name":[],"type":[]}
             * building : {"name":[],"type":[]}
             * adcode : 440310
             * street : []
             * number : []
             * location : 114.360910,22.678323
             * level : 兴趣点
             */
    
            private String formatted_address;
            private String province;
            private String citycode;
            private String city;
            private String district;
            private NeighborhoodBean neighborhood;
            private BuildingBean building;
            private String adcode;
            private String location;
            private String level;
            private List<?> township;
            private List<?> street;
            private List<?> number;
    
            public String getFormatted_address() {
                return formatted_address;
            }
    
            public void setFormatted_address(String formatted_address) {
                this.formatted_address = formatted_address;
            }
    
            public String getProvince() {
                return province;
            }
    
            public void setProvince(String province) {
                this.province = province;
            }
    
            public String getCitycode() {
                return citycode;
            }
    
            public void setCitycode(String citycode) {
                this.citycode = citycode;
            }
    
            public String getCity() {
                return city;
            }
    
            public void setCity(String city) {
                this.city = city;
            }
    
            public String getDistrict() {
                return district;
            }
    
            public void setDistrict(String district) {
                this.district = district;
            }
    
            public NeighborhoodBean getNeighborhood() {
                return neighborhood;
            }
    
            public void setNeighborhood(NeighborhoodBean neighborhood) {
                this.neighborhood = neighborhood;
            }
    
            public BuildingBean getBuilding() {
                return building;
            }
    
            public void setBuilding(BuildingBean building) {
                this.building = building;
            }
    
            public String getAdcode() {
                return adcode;
            }
    
            public void setAdcode(String adcode) {
                this.adcode = adcode;
            }
    
            public String getLocation() {
                return location;
            }
    
            public void setLocation(String location) {
                this.location = location;
            }
    
            public String getLevel() {
                return level;
            }
    
            public void setLevel(String level) {
                this.level = level;
            }
    
            public List<?> getTownship() {
                return township;
            }
    
            public void setTownship(List<?> township) {
                this.township = township;
            }
    
            public List<?> getStreet() {
                return street;
            }
    
            public void setStreet(List<?> street) {
                this.street = street;
            }
    
            public List<?> getNumber() {
                return number;
            }
    
            public void setNumber(List<?> number) {
                this.number = number;
            }
    
            public static class NeighborhoodBean {
                private List<?> name;
                private List<?> type;
    
                public List<?> getName() {
                    return name;
                }
    
                public void setName(List<?> name) {
                    this.name = name;
                }
    
                public List<?> getType() {
                    return type;
                }
    
                public void setType(List<?> type) {
                    this.type = type;
                }
            }
    
            public static class BuildingBean {
                private List<?> name;
                private List<?> type;
    
                public List<?> getName() {
                    return name;
                }
    
                public void setName(List<?> name) {
                    this.name = name;
                }
    
                public List<?> getType() {
                    return type;
                }
    
                public void setType(List<?> type) {
                    this.type = type;
                }
            }
        }
    
    

    然后解析的函数就好写了:

     private void parseJSONWithGSON(String jsonData){
            Gson gson =new Gson();
            Location jdata=gson.fromJson(jsonData,Location .class);//解析掉第一层
            List<GeocodesBean> beanList= jdata .getGeocodes();//getGeocodes()得到的就是一个数组[],封装为list
            Log.e("TAG","location:"+beanList.get(0).getLocation());//list的第一个(即序号0)的数据中就含有location
            }
    

    这样就可以打印出经纬度数据了。

    10月9日下午2点更新
    这个解析部分在解析地址为市级别和省级别(比如深圳,香港)的时候,解析部分会发生崩溃。
    查看具体地点名,城市名,省级行政区三种情况的Json数据
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

    发现区别只在3个参数:city,citycode,district,所以去GeocodesBean.java中把它们注释掉就好了。
    更改后的GeocodesBean.java

    public class GeocodesBean {
            /**
             * formatted_address : 广东省深圳市坪山区六角大楼
             * province : 广东省
             * citycode : 0755
             * city : 深圳市
             * district : 坪山区
             * township : []
             * neighborhood : {"name":[],"type":[]}
             * building : {"name":[],"type":[]}
             * adcode : 440310
             * street : []
             * number : []
             * location : 114.360910,22.678323
             * level : 兴趣点
             */
    
            private String formatted_address;
            private String province;
            /*private String citycode;
            private String city;
            private String district;*/ //注释掉这些就可以查询市,省级级别的地区了,比如香港,广东,深圳等
            private NeighborhoodBean neighborhood;
            private BuildingBean building;
            private String adcode;
            private String location;
            private String level;
            private List<?> township;
            private List<?> street;
            private List<?> number;
    
            public String getFormatted_address() {
                return formatted_address;
            }
    
            public void setFormatted_address(String formatted_address) {
                this.formatted_address = formatted_address;
            }
    
            public String getProvince() {
                return province;
            }
    
            public void setProvince(String province) {
                this.province = province;
            }
    
           /* public String getCitycode() {
                return citycode;
            }
    
            public void setCitycode(String citycode) {
                this.citycode = citycode;
            }
    
            public String getCity() {
                return city;
            }
    
            public void setCity(String city) {
                this.city = city;
            }
    
            public String getDistrict() {
                return district;
            }
    
            public void setDistrict(String district) {
                this.district = district;
            }*/
    
            public NeighborhoodBean getNeighborhood() {
                return neighborhood;
            }
    
            public void setNeighborhood(NeighborhoodBean neighborhood) {
                this.neighborhood = neighborhood;
            }
    
            public BuildingBean getBuilding() {
                return building;
            }
    
            public void setBuilding(BuildingBean building) {
                this.building = building;
            }
    
            public String getAdcode() {
                return adcode;
            }
    
            public void setAdcode(String adcode) {
                this.adcode = adcode;
            }
    
            public String getLocation() {
                return location;
            }
    
            public void setLocation(String location) {
                this.location = location;
            }
    
            public String getLevel() {
                return level;
            }
    
            public void setLevel(String level) {
                this.level = level;
            }
    
            public List<?> getTownship() {
                return township;
            }
    
            public void setTownship(List<?> township) {
                this.township = township;
            }
    
            public List<?> getStreet() {
                return street;
            }
    
            public void setStreet(List<?> street) {
                this.street = street;
            }
    
            public List<?> getNumber() {
                return number;
            }
    
            public void setNumber(List<?> number) {
                this.number = number;
            }
    
            public static class NeighborhoodBean {
                private List<?> name;
                private List<?> type;
    
                public List<?> getName() {
                    return name;
                }
    
                public void setName(List<?> name) {
                    this.name = name;
                }
    
                public List<?> getType() {
                    return type;
                }
    
                public void setType(List<?> type) {
                    this.type = type;
                }
            }
    
            public static class BuildingBean {
                private List<?> name;
                private List<?> type;
    
                public List<?> getName() {
                    return name;
                }
    
                public void setName(List<?> name) {
                    this.name = name;
                }
    
                public List<?> getType() {
                    return type;
                }
    
                public void setType(List<?> type) {
                    this.type = type;
                }
            }
        }
    
    

    最后搞定啦

    展开全文
  • http://stackoverflow.com/questions/14139437/java-type-generic-as-argument-for-gson 转载于:https://www.cnblogs.com/justang/p/5672058.html

    http://stackoverflow.com/questions/14139437/java-type-generic-as-argument-for-gson

    转载于:https://www.cnblogs.com/justang/p/5672058.html

    展开全文
  • 使用Gson解析两种复杂的json数据

    千次阅读 2016-09-12 11:10:11
    众所周知,我们在做新闻、天气预报等类型的app的时候,经常会碰到需要将获取的json网络数据进行数据解析,以方便我们获取需要的信息并进行封装显示,这时候我们有两种解析方式:原生解析Gson框架解析;  接下来就...

             众所周知,我们在做新闻、天气预报等类型的app的时候,经常会碰到需要将获取的json网络数据进行数据解析,以方便我们获取需要的信息并进行封装显示,这时候我们有两种解析方式:原生解析和Gson框架解析;

            接下来就这两种解析方式进行一个总结:

           一:Gson框架解析

    注意:在我们进行实体类封装时,我们需要获取的数据,如果有父类,我们也需要将父类封装起来,不然我们就获取不到子类即我们需要的数据信息;

                封装的实体类,必须和json数据的key名字完全一致,否则无法解析;

           Gson框架的下载地址我就不贴出来了,这里只要讲解两种不同类型的json数据的实体封装及利用框架进行数据解析;


            请注意一下两种json数据的不同:   
    第一种:

    {
        "reason": "成功的返回",
        "result": {
            "stat": "1",
            "data": [
                {
                    "title": "男有陈冠希,女有张静初,专业睡导演30年惨遭导演太太集体封杀",
                    "date": "2016-09-12 06:18",
                    "author_name": "分合晚歌",
                    "thumbnail_pic_s": "http://07.imgmini.eastday.com/mobile/20160912/20160912061828_8c09ffce02b767cdc68d09a680e44625_1_mwpm_03200403.jpeg",
                    "thumbnail_pic_s02": "http://07.imgmini.eastday.com/mobile/20160912/20160912061828_8c09ffce02b767cdc68d09a680e44625_1_mwpl_05500201.jpeg",
                    "thumbnail_pic_s03": "http://07.imgmini.eastday.com/mobile/20160912/20160912061828_8c09ffce02b767cdc68d09a680e44625_1_mwpl_05500201.jpeg",
                    "url": "http://mini.eastday.com/mobile/160912061828549.html?qid=juheshuju",
                    "uniquekey": "160912061828549",
                    "type": "头条",
                    "realtype": "娱乐"
                },
                {
                    "title": "赵薇怎么又胖又老,和林心如比起来差这么多?",
                    "date": "2016-09-12 06:08",
                    "author_name": "最美Angelababy",
                    "thumbnail_pic_s": "http://08.imgmini.eastday.com/mobile/20160912/20160912060823_028c9d44155b206f0fc3b5306506fca7_1_mwpm_03200403.jpeg",
                    "thumbnail_pic_s02": "http://08.imgmini.eastday.com/mobile/20160912/20160912060823_028c9d44155b206f0fc3b5306506fca7_1_mwpl_05500201.jpeg",
                    "thumbnail_pic_s03": "http://08.imgmini.eastday.com/mobile/20160912/20160912060823_028c9d44155b206f0fc3b5306506fca7_1_mwpl_05500201.jpeg",
                    "url": "http://mini.eastday.com/mobile/160912060823513.html?qid=juheshuju",
                    "uniquekey": "160912060823513",
                    "type": "头条",
                    "realtype": "娱乐"
                },
      

    第二种:
    {
        "error": 0,
        "status": "success",
        "date": "2014-05-10",
        "results": [
            {
                "currentCity": "南京",
                "weather_data": [
                    {
                        "date": "周六(今天, 实时:19℃)",
                        "dayPictureUrl": "http://api.map.baidu.com/images/weather/day/dayu.png",
                        "nightPictureUrl": "http://api.map.baidu.com/images/weather/night/dayu.png",
                        "weather": "大雨",
                        "wind": "东南风5-6级",
                        "temperature": "18℃"
                    },
                    {
                        "date": "周日",
                        "dayPictureUrl": "http://api.map.baidu.com/images/weather/day/zhenyu.png",
                        "nightPictureUrl": "http://api.map.baidu.com/images/weather/night/duoyun.png",
                        "weather": "阵雨转多云",
                        "wind": "西北风4-5级",
                        "temperature": "21 ~ 14℃"
                    }
                ]
            }
        ]
    }

            第一种在我们需要获取的数据“data”的上方,我们需要先封装出“result”的实体类,然而其为

    "result": {
            "stat": "1",
            "data": [

          这样的一种形式,而第二种的json数据类型,在我们需要获取“weather_data”的数据的上方,我们需要先封装出“results”的实体类,然而其为

    "results": [
           {
              "currentCity": "南京",
              "weather_data": [

     不难看出,第一种的“result”后面跟着的是一个花括号,第二种“results”后面跟着一个中括号和一个花括号,这两种有什么不同呢?


     首先:第一种数据的“result”后面跟着一个花括号,这代表着,这个“result”我们可以把它当做是一个类来封装起来,它的类型就是下面的数据的类型,这个可以由我们来命名,那么它的实体封装方式,如下:

    result封装:

    public class NewsResult {
    	
    	private News result;
    
    	public News getResult() {
    		return result;
    	}
    
    	public void setResult(News result) {
    		this.result = result;
    	}
    
    	@Override
    	public String toString() {
    		return "NewsResult [result=" + result + "]";
    	}
    }
    news封装
    public class News {
    
    	private String stat;
    	private List
        
          data;
    	
    	
    	public String getStat() {
    		return stat;
    	}
    	public void setStat(String stat) {
    		this.stat = stat;
    	}
    	public List
         
           getData() {
    		return data;
    	}
    	public void setData(List
          
            data) {
    		this.data = data;
    	}
    	public News(String stat, List
           
             data) {
    		super();
    		this.stat = stat;
    		this.data = data;
    	}
    	
    	
    }
           
          
         
        
    newsItem封装
    public class NewsItem {
    
    	/**
    	 * 标题
    	 */
    	private String title;
    	/**
    	 * 时间
    	 */
    	private String date;
    	/**
    	 * 作者
    	 */
    	private String author_name;
    	/**
    	 * 图片1
    	 */
    	private String thumbnail_pic_s;
    	/**
    	 * 图片2
    	 */
    	private String thumbnail_pic_s02;
    	/**
    	 * 图片3
    	 */
    	private String thumbnail_pic_s03;
    	/**
    	 * 网址链接
    	 */
    	private String url;
    	/**
    	 * 唯一标识
    	 */
    	private long uniquekey;
    	/**
    	 * 类型1
    	 */
    	private String type;
    	/**
    	 * 类型2
    	 */
    	private String realtype;
    	public String getTitle() {
    		return title;
    	}
    	public void setTitle(String title) {
    		this.title = title;
    	}
    	public String getDate() {
    		return date;
    	}
    	public void setDate(String date) {
    		this.date = date;
    	}
    	public String getAuthor_name() {
    		return author_name;
    	}
    	public void setAuthor_name(String author_name) {
    		this.author_name = author_name;
    	}
    	public String getThumbnail_pic_s() {
    		return thumbnail_pic_s;
    	}
    	public void setThumbnail_pic_s(String thumbnail_pic_s) {
    		this.thumbnail_pic_s = thumbnail_pic_s;
    	}
    	public String getThumbnail_pic_s02() {
    		return thumbnail_pic_s02;
    	}
    	public void setThumbnail_pic_s02(String thumbnail_pic_s02) {
    		this.thumbnail_pic_s02 = thumbnail_pic_s02;
    	}
    	public String getThumbnail_pic_s03() {
    		return thumbnail_pic_s03;
    	}
    	public void setThumbnail_pic_s03(String thumbnail_pic_s03) {
    		this.thumbnail_pic_s03 = thumbnail_pic_s03;
    	}
    	public String getUrl() {
    		return url;
    	}
    	public void setUrl(String url) {
    		this.url = url;
    	}
    	public long getUniquekey() {
    		return uniquekey;
    	}
    	public void setUniquekey(long uniquekey) {
    		this.uniquekey = uniquekey;
    	}
    	public String getType() {
    		return type;
    	}
    	public void setType(String type) {
    		this.type = type;
    	}
    	public String getRealtype() {
    		return realtype;
    	}
    	public void setRealtype(String realtype) {
    		this.realtype = realtype;
    	}
    	@Override
    	public String toString() {
    		return "NewsItem [title=" + title + ", date=" + date + ", author_name="
    				+ author_name + ", thumbnail_pic_s=" + thumbnail_pic_s
    				+ ", thumbnail_pic_s02=" + thumbnail_pic_s02
    				+ ", thumbnail_pic_s03=" + thumbnail_pic_s03 + ", url=" + url
    				+ ", uniquekey=" + uniquekey + ", type=" + type + ", realtype="
    				+ realtype + "]";
    	}
    
    	
    }
     在这里,我们的result是一个类的封装,那么它的类型就是News类的类型,在News类中的数据“data”,它可以由一个集合来将其封装起来,NewsItem为集合中“data”的每一个元素,这时我们的实体类就已经封装好了,在接下来进行Gson解析,如下:

    				//创建Gson对象
    				Gson gson = new Gson();
    				//根据NewsResult的封装实体类进行解析
    				NewsResult newsResult = gson.fromJson(response, NewsResult.class);
    				//创建集合
    				List
        
          newsItems = new ArrayList
         
          ();
    				//将解析后的数据赋值给集合,以实现其他类的调用
    				newsItems = newsResult.getResult().getData();
         
        

     然后:第二种数据的“results”后面跟着的是一个中括号,中括号后面还跟着一个花括号,这表示我们的“results”的封装可以将其作为一个集合的方式进行封装,如下:

    weatherResult封装

    public class WeatherResult {
    	 private String error;  
         private String status;  
         private String date;  
         private List
        
          results;
         
    	public String getError() {
    		return error;
    	}
    	public void setError(String error) {
    		this.error = error;
    	}
    	public String getStatus() {
    		return status;
    	}
    	public void setStatus(String status) {
    		this.status = status;
    	}
    	public String getDate() {
    		return date;
    	}
    	public void setDate(String date) {
    		this.date = date;
    	}
    	public List
         
           getResults() {
    		return results;
    	}
    	public void setResults(List
          
            results) {
    		this.results = results;
    	}
    	@Override
    	public String toString() {
    		return "WeatherResult [error=" + error + ", status=" + status
    				+ ", date=" + date + "]";
    	} 
         
         
    }
    
          
         
        
    results封装

    public class Results   {     
    	private String currentCity;  
    	private List
        
          weather_data;
    	
    	public String getCurrentCity() {
    		return currentCity;
    	}
    	public void setCurrentCity(String currentCity) {
    		this.currentCity = currentCity;
    	}
    	public List
         
           getWeather_data() {
    		return weather_data;
    	}
    	public void setWeather_data(List
          
            weather_data) {
    		this.weather_data = weather_data;
    	}
    	@Override
    	public String toString() {
    		return "Results [currentCity=" + currentCity + "]";
    	} 
    	
    	
    }
          
         
        
    weather封装

    public class Weather {  
    	private String date;  
    	private String dayPictureUrl;  
    	private String nightPictureUrl;  
    	private String weather;  
    	private String wind;  
    	private String temperature;
    	
    	public String getDate() {
    		return date;
    	}
    	public void setDate(String date) {
    		this.date = date;
    	}
    	public String getDayPictureUrl() {
    		return dayPictureUrl;
    	}
    	public void setDayPictureUrl(String dayPictureUrl) {
    		this.dayPictureUrl = dayPictureUrl;
    	}
    	public String getNightPictureUrl() {
    		return nightPictureUrl;
    	}
    	public void setNightPictureUrl(String nightPictureUrl) {
    		this.nightPictureUrl = nightPictureUrl;
    	}
    	public String getWeather() {
    		return weather;
    	}
    	public void setWeather(String weather) {
    		this.weather = weather;
    	}
    	public String getWind() {
    		return wind;
    	}
    	public void setWind(String wind) {
    		this.wind = wind;
    	}
    	public String getTemperature() {
    		return temperature;
    	}
    	public void setTemperature(String temperature) {
    		this.temperature = temperature;
    	}
    	@Override
    	public String toString() {
    		return "Weather [date=" + date + ", dayPictureUrl=" + dayPictureUrl
    				+ ", nightPictureUrl=" + nightPictureUrl + ", weather="
    				+ weather + ", wind=" + wind + ", temperature=" + temperature
    				+ "]";
    	}
    	
    	
    	
    }
     在这里,我们可以理解成,碰到只有花括号的,我们就将花括号的要封装的内容作为它子类类型的一个类进行封装;碰到是中括号加花括号的,我们在封装时就当做一个集合来进行封装,子类则为集合的元素

     下面进行Gson解析,如下:

     Gson gson = new Gson();
     WeatherResult weatherResult = gson.fromJson(response, WeatherResult.class); 
     List
        
          result = new ArrayList
         
          ;
     result = weatherResult.getResults().getWeather_data();  
                             
         
        

      二:原生解析

        json数据的原生解析,即根据json的数据类型进行一步步往下解析,当碰到只有花括号时,我们就用getJSONObject()方法解析;当碰到外层中括号,内层花括号时,我们就用getJSONArray()方法解析,然后遍历它里面的内容即可,这里第一种json数据的原生解析方式如下:

    实体类封装

    import java.util.ArrayList;
    import java.util.List;
    
    public class NewsItem {
    	/**
    	 * 封装News集合
    	 */
    	private List
        
          data;
    	
    	/**
    	 * 单次请求数据返回数据
    	 */
    	private String stat;
    	
    	public String getStat() {
    		return stat;
    	}
    
    	public void setStat(String stat) {
    		this.stat = stat;
    	}
    
    	public NewsItem(List
         
           data) {
    		super();
    		this.data = data;
    	}
    
    	public List
          
            getData() {
    		return data;
    	}
    
    	public void setData(List
           
             data) {
    		this.data = data;
    	}
    	
    }
    
           
          
         
        
    import java.io.Serializable;
    
    /**
     * 新闻实体类
     */
    public class News implements Serializable{
    	private String title;
    	private String date;
    	private String author_name;
    	private String thumbnail_pic_s;
    	private String thumbnail_pic_s02;
    	private String thumbnail_pic_s03;
    	private String url;
    	private String uniquekey;
    	private String type;
    	private String realtype;
    	public News(){
    		
    	}
    	public News(String title, String date, String author_name,
    			String thumbnail_pic_s, String thumbnail_pic_s02,
    			String thumbnail_pic_s03, String url, String uniquekey,
    			String type, String realtype) {
    		super();
    		this.title = title;
    		this.date = date;
    		this.author_name = author_name;
    		this.thumbnail_pic_s = thumbnail_pic_s;
    		this.thumbnail_pic_s02 = thumbnail_pic_s02;
    		this.thumbnail_pic_s03 = thumbnail_pic_s03;
    		this.url = url;
    		this.uniquekey = uniquekey;
    		this.type = type;
    		this.realtype = realtype;
    	}
    	public String getTitle() {
    		return title;
    	}
    	public void setTitle(String title) {
    		this.title = title;
    	}
    	public String getDate() {
    		return date;
    	}
    	public void setDate(String date) {
    		this.date = date;
    	}
    	public String getAuthor_name() {
    		return author_name;
    	}
    	public void setAuthor_name(String author_name) {
    		this.author_name = author_name;
    	}
    	public String getThumbnail_pic_s() {
    		return thumbnail_pic_s;
    	}
    	public void setThumbnail_pic_s(String thumbnail_pic_s) {
    		this.thumbnail_pic_s = thumbnail_pic_s;
    	}
    	public String getThumbnail_pic_s02() {
    		return thumbnail_pic_s02;
    	}
    	public void setThumbnail_pic_s02(String thumbnail_pic_s02) {
    		this.thumbnail_pic_s02 = thumbnail_pic_s02;
    	}
    	public String getThumbnail_pic_s03() {
    		return thumbnail_pic_s03;
    	}
    	public void setThumbnail_pic_s03(String thumbnail_pic_s03) {
    		this.thumbnail_pic_s03 = thumbnail_pic_s03;
    	}
    	public String getUrl() {
    		return url;
    	}
    	public void setUrl(String url) {
    		this.url = url;
    	}
    	public String getUniquekey() {
    		return uniquekey;
    	}
    	public void setUniquekey(String uniquekey) {
    		this.uniquekey = uniquekey;
    	}
    	public String getType() {
    		return type;
    	}
    	public void setType(String type) {
    		this.type = type;
    	}
    	public String getRealtype() {
    		return realtype;
    	}
    	public void setRealtype(String realtype) {
    		this.realtype = realtype;
    	}
    	@Override
    	public String toString() {
    		return "News [title=" + title + ", date=" + date + ", author_name="
    				+ author_name + ", thumbnail_pic_s=" + thumbnail_pic_s
    				+ ", thumbnail_pic_s02=" + thumbnail_pic_s02
    				+ ", thumbnail_pic_s03=" + thumbnail_pic_s03 + ", url=" + url
    				+ ", uniquekey=" + uniquekey + ", type=" + type + ", realtype="
    				+ realtype + "]";
    	}
    	
    }
    

    原生解析:

    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    import android.util.Log;
    
    import com.android.volley.AuthFailureError;
    import com.android.volley.Request;
    import com.android.volley.RequestQueue;
    import com.android.volley.Response;
    import com.android.volley.VolleyError;
    import com.android.volley.toolbox.StringRequest;
    import com.android.volley.toolbox.Volley;
    
    import com.google.gson.Gson;
    import com.google.gson.JsonObject;
    
    import com.wjt.plamworld.PlamWorldApplication;
    import com.wjt.plamworld.entity.News;
    import com.wjt.plamworld.entity.NewsItem;
    import com.wjt.plamworld.model.IMainNewsModel;
    import com.wjt.plamworld.util.GlobalConsts;
    
    
    
    /**
     * 新闻客户端主页的网络请求
     *
     */
    public class MainNewsModelImpl implements IMainNewsModel {
    	/**
    	 * volley框架消息列队对象
    	 */
    
    	private RequestQueue rq = Volley.newRequestQueue(PlamWorldApplication.getContext());
    	@Override
    	public void loadData(final Map
        
          urlParam, final MainNewsCallBack callBack) {
    		//运用volley框架进行服务器接口访问,并得到json数据String
    				StringRequest sr = new StringRequest(Request.Method.POST, GlobalConsts.URL_NEW_MAIN, 
    						new Response.Listener
         
          () {
    					List
          
           list=new ArrayList
           
            ();
    					@Override
    					public void onResponse(String response) {
    						
    						//用Json的方法
    						try {
    							JSONObject object=new JSONObject(response);
    							JSONObject result=object.getJSONObject("result");
    							JSONArray array=result.getJSONArray("data");
    							for(int i=0;i
            
              getParams() throws AuthFailureError { return urlParam; } }; rq.add(sr); } } 
            
           
          
         
        

    展开全文
  • 碰到类似如下格式的json,总是解析失败,希望大神帮助解析一下 { "code":0, "message":"", "data":[ { "info":{"id":0,"name":"lina","age":10}, "subclass":[] }, { "info":{"id":1,"name":"may",...
  • Gson解析嵌套json

    千次阅读 2016-07-28 15:55:52
    Gson解析嵌套json
  • 使用Gson解析复杂的json数据

    万次阅读 多人点赞 2014-06-25 18:48:53
    Gson解析复杂的json数据
  • WeatherBean bean = new Gson().fromJson(weatherMessage, WeatherBean.class); 2.获取json字符串中的某个参数 JsonObject jsonObject = new JsonParser().parse(msg).getAsJsonObject(); St...
  • 前言:看了好多gson解析多层json的博客都不尽如人意,都在jsonbean这就结束了,我想要后面将json转换成对象的部分啊 于是自己动手丰衣足食,我终于让我在庞大的云盘库里找到了,开心。但是我还是不熟悉多层,我多...
  • Gson解析嵌套JSON格式数据

    千次阅读 2015-12-15 12:29:54
    来源说明:最近在无聊,刚刚又想学一下安卓的APP, 刚刚好看到"中国天气网...刚刚好又想到用GSON解析,我学了一下. 1.数据格式{ "user":"zhangsan", "c": { "c1": "101010100", "c2": "beijing" }, "f": { "f1": [{
  • 主要是区分typetoken里的类型,多层嵌套的话,最外层也需要加上泛型T,如果不是正确类型,body的泛型T会返回的是map数据结构 1、第一层 public class GeneralRespose<T> { /* { "Response": { "Head": { ...
  • Gson多层嵌套Json解析

    2015-06-16 08:28:42
    多层嵌套Json解析 采用静态内部类的形式实现多层嵌套 对于数组采用List成员实现   { "mp3list": [  {  "name": "爱我别走",  "artist": "张震岳",  "size": "2.8M",  "url": "http://127.0.0.1"
  • Kotlin配合Gson进行json数据解析

    千次阅读 2018-01-12 02:24:05
    Kotlin配合Gson进行json数据解析 昨天写的小demo里使用到了这个 1,首先引入第3方库 implementation 'com.squareup.okhttp3:okhttp:3.8.1' implementation 'io.reactivex.rxjava2:rxjava:2.1.2' implementation 'io...
  • Gson解析json

    2016-08-25 17:22:52
    本文转载链接为:http://www.cnblogs.com/chenlhuaf/archive/2011/05/01/gson_test.html 下面是一个简单的例子: Person实体 ...上面的代码重点是Gson对象,它提供了toJason()方法将对象转换成Json字符
  • 讲一个比较简单点的例子,帮助理解Gson的简单的... 比如我们要解析一个下面这种的Json:  String json = {"a":"100","b":[{"b1":"b_value1","b2":"b_value2"},{"b1":"b_value1","b2":"b_value2"}],"c":{"c1":"c_va
  • 这种数据也不好说是啥样的,也只好给你先看看 [{"name":"test123","description":"","resolution":1,"map":"5cac4cf6664d590858744ff8","parent":"root","id":"5cac4cf6c3c74106486f2aa6","permissions":["*"]}] ...
  • Gson解析嵌套多层Json

    千次阅读 2016-04-01 14:38:05
    首先先讲一个比较简单点的例子(最简单的我就不讲啦,网上很多),帮助新手理解Gson的使用方法: 比如我们要解析一个下面这种的Json:    String json = {"a":"100","b":[{"b1":"b_value1","b2":"b_value2"}
  • 首先先讲一个比较简单点的例子(最简单的我就不讲啦,网上很多),帮助... 比如我们要解析一个下面这种的Json:  String json = {"a":"100","b":[{"b1":"b_value1","b2":"b_value2"},{"b1":"b_value1","b2":"b_value2
  • 运用Gson解析Json的方法步骤: 先对应网页上的内容创建实体类,创建实体类的方法: 如果是同一级的,则只需要将其声明便可过程中可用@SerializedName来将网页中的字符与自己创建的字符对应起来 public ...
  • 首先需要设计Json解析后保存的关系型数据库表结构,包括主表,附表,各表的主键和外键; 解析详细代码如下: package jsonparser; import com.google.gson.JsonArray; import com.google.gson.JsonElement; ...
  • 1.如果使用gson我们首先要导入gson的依赖: implementation 'com.google.code.gson:gson:2.8.6' 2.工具类实现:JsonUtil package com.antbyte.collectionorder.utils.data; import android.text.TextUtils; ...
  • Android解析多层json数据并用递归进行查找 采用Gson进行json字符串的解析,然后利用递归进行特定数据的查找。 需要处理的数据 首先,需要处理的json长这样 { "code":10, "data":[ { "children":[ { ...
  • android Gson多维Json数组解析

    千次阅读 2019-04-18 14:29:58
    解析Json数据时,遇到二维数组或者更多维的数组的处理方法。 Json如下: {"code": 1, "data": [ [ { "nodename": "测试", "addr": "中国北京市xx区xx路x号", "uid": "123", } ]...
  • 通过获取JsonReader对象解析JSON数据: String jsonData = "[{\"username\":\"arthinking\",\"userId\":001},{\"username\":\"Jason\",\"userId\":002}]"; try{ JsonReader reader = new JsonReader(new...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 426
精华内容 170
关键字:

gson解析多层json数据