Android开发--使用实体类解析JSON文本

来源:互联网 发布:godaddy域名续费好贵 编辑:程序博客网 时间:2024/06/04 01:32

Android开发–使用实体类解析JSON文本

在Android开发过程中,涉及到了API的调用的时候,会返回特定的数据,两个主流返回的数据格式是JSON形式和XML形式。但是相对于XML,JSON数据格式有着比较简单,易于读写,格式都是压缩的,占用带宽小等优点,这里介绍的是JSON文本的解析,采用的方法是实体类解析。


  1. 准备:

    这里使用的是谷歌的JSON解析—GSON:

    文件地址:http://download.csdn.net/detail/qq_34861102/9922580

    放入libs目录之后导入:compile files('libs/gson-2.2.1.jar')

  2. 实际例子:

    首先说明一下:

    JSON的实体类是有专门的工具生成的,详情看链接:http://tool.chinaz.com/tools/json2entity.aspx

    但是在这里建议第一次使用实体类熟悉一下实体类分析的流程:

    • 先来一个比较复杂的JSON文本:
    {"showapi_res_code":0,"showapi_res_error":"","showapi_res_body":{"ret_code":0,"pagebean":{"allPages":1,"contentlist":[{"summary":"奇山、异水、怪洞、珍禽数不胜数。","proId":"13","cityId":"0","location":{"lon":"109.17992791","lat":"30.47104117"},"priceList":[{"entityList":[{"TicketName":"【恩施大峡谷】七星寨+云龙河地缝+索道上行+景区观光车","Amount":"270","BeginDate":"2015-12-01","EndDate":"2016-02-29","PriceName":"淡季(2015.12.1-2016.2.29)","TicketTypeId":188798,"AmountAdvice":"250","PriceInSceneryId":25710,"PriceId":242390}],"type":"成人票"},{"entityList":[{"TicketName":"【恩施大峡谷】七星寨景区+云龙河地缝+景区观光车","Amount":"160","BeginDate":"2015-12-01","EndDate":"2016-02-29","PriceName":"淡季(2015.12.1-2016.2.29)","TicketTypeId":188774,"AmountAdvice":"150","PriceInSceneryId":25710,"PriceId":242457}],"type":"组合优惠票"},{"entityList":[{"TicketName":"恩施大峡谷+富源国宾酒店","Amount":"1028","TicketTypeId":0,"AmountAdvice":"785","PriceInSceneryId":0,"PriceId":0},{"TicketName":"恩施大峡谷+恩施大峡谷女儿寨度假酒店+双份早餐","Amount":"1248","TicketTypeId":0,"AmountAdvice":"778","PriceInSceneryId":0,"PriceId":0},{"TicketName":"恩施大峡谷+恩施腾龙洞+富源国宾酒店2晚","Amount":"1876","TicketTypeId":0,"AmountAdvice":"1292","PriceInSceneryId":0,"PriceId":0}],"type":"酒店+景点"}],"areaId":"0","ct":"2016-01-22 01:46:36.900","content":"与大多数名山的云海显得闲散无序不同的是,恩施大峡谷里从清江上升起的云海象一条腾飞的巨龙,蜿蜒曲折,延绵百里,形态丰润,美不胜收。喀斯特地貌一般情形是有绝壁者无峰丛,有峰丛者无绝壁,恩施大峡谷不仅兼而有之,而且面积之大、品位之高。有四面绝壁凹陷于丛峰之中,也有四面绝壁突出似凌架于丛峰之上。世界上目前尚未 发现类似奇景。据不完全统计,大峡谷沿线有大小洞穴200余个。如板桥的热云洞,有石壁相隔形成两个洞口,一洞通热风,一洞出冷风,冷热交融烟雾缭绕,而且洞内的大厅可容纳数万,更有天桥匹配,水天相谐 、人物相映,犹如仙境。曾游历欧美的张良皋教授将清江大峡谷与美洲的科罗拉多大峡谷相比。他说,论壮观,科罗拉多大峡谷与清江大峡谷不过伯仲之间,论美丽,恩施大峡谷的沐抚段实在无与伦比。八百里清江中,恩施 屯堡至沐抚的大峡谷,以气势雄阔的绝壁险峰,称奇于世。恩施大峡谷大型山水实景音乐剧《龙船调》共四幕,*场 春•咒怨;第二场夏•选瓜; 第三场秋•骂神;第四场冬•融冰。《龙船调》讲述了一个受诅咒的土司女儿和艄公儿子从相遇到相知,*后突破重重阻隔终成眷属的故事。整场音乐剧充满着浓浓的土家风情,真正的荡气回肠,让您久久不能忘怀。","id":"25710","proName":"湖北","price":"150.00","address":"湖北省恩施市西北部沐抚办事处境内","name":"恩施大峡谷","opentime":"08:30-16:00","coupon":"A.免票政策:儿童身高1.2米(包含)以下免费;70周岁(包含)以上老年人凭老年证或身份证、现役军人凭军官证或士兵证、残疾人凭残疾证、国家新闻出版署颁发的记者证、导游带团持国家旅游局颁发的导游证免票。B.优惠政策:6(包含)-18岁(包含)之间的在校全日制学生凭学生证、60至70周岁(不含)之间老人(凭老年证或身份证)购景区优惠票(上述优惠政策仅作参考,需到景区自行购买)。","attention":"①预订成人票包含七星寨景区、云龙河地缝景区的参观票。②预订门票+索道上行包含七星寨景区、云龙河地缝景区的参观票,索道上行的单程票。③另付费项目:景区内车票、索道下行、索道往返、电梯需另付费。④门票当天有效,出园需入园,请再次购票。⑤为保证取票、入园顺利,预订时请务必填写真实姓名、手机号码等信息。⑥自2015.11.3开始,景区内索道每天下午3点停止运营,请游客做好出行准备,掌握好游览时间。\r\n活动提醒1.武汉心发现 让更多的人享受旅游生活的乐趣","picList":[{"picUrl":"http://pic3.40017.cn/scenery/destination/2015/08/24/18/GvsblZ.jpg","picUrlSmall":"http://pic3.40017.cn/scenery/destination/2015/08/24/18/GvsblZ_130x130_00.jpg"},{"picUrl":"http://pic3.40017.cn/scenery/destination/2015/08/24/18/V2dqxx.jpg","picUrlSmall":"http://pic3.40017.cn/scenery/destination/2015/08/24/18/V2dqxx_130x130_00.jpg"},{"picUrl":"http://pic3.40017.cn/scenery/destination/2015/08/24/18/buc37a.jpg","picUrlSmall":"http://pic3.40017.cn/scenery/destination/2015/08/24/18/buc37a_130x130_00.jpg"},{"picUrl":"http://pic3.40017.cn/scenery/destination/2015/08/24/18/KtRjwt.jpg","picUrlSmall":"http://pic3.40017.cn/scenery/destination/2015/08/24/18/KtRjwt_130x130_00.jpg"},{"picUrl":"http://pic3.40017.cn/scenery/destination/2015/08/24/18/I1pLZj.jpg","picUrlSmall":"http://pic3.40017.cn/scenery/destination/2015/08/24/18/I1pLZj_130x130_00.jpg"},{"picUrl":"http://pic3.40017.cn/scenery/destination/2015/08/24/18/N1sXJe.jpg","picUrlSmall":"http://pic3.40017.cn/scenery/destination/2015/08/24/18/N1sXJe_130x130_00.jpg"},{"picUrl":"http://pic3.40017.cn/scenery/destination/2015/04/17/22/rPi5dA.jpg","picUrlSmall":"http://pic3.40017.cn/scenery/destination/2015/04/17/22/rPi5dA_130x130_00.jpg"},{"picUrl":"http://pic3.40017.cn/scenery/destination/2015/04/17/22/bPy78i.jpg","picUrlSmall":"http://pic3.40017.cn/scenery/destination/2015/04/17/22/bPy78i_130x130_00.jpg"},{"picUrl":"http://pic3.40017.cn/scenery/destination/2015/04/17/22/kLAESW.jpg","picUrlSmall":"http://pic3.40017.cn/scenery/destination/2015/04/17/22/kLAESW_130x130_00.jpg"},{"picUrl":"http://pic3.40017.cn/scenery/destination/2015/04/17/22/ElWZin.jpg","picUrlSmall":"http://pic3.40017.cn/scenery/destination/2015/04/17/22/ElWZin_130x130_00.jpg"},{"picUrl":"http://pic3.40017.cn/scenery/destination/2015/04/17/22/G9XA6G.jpg","picUrlSmall":"http://pic3.40017.cn/scenery/destination/2015/04/17/22/G9XA6G_130x130_00.jpg"},{"picUrl":"http://pic3.40017.cn/scenery/destination/2015/04/17/22/pfbf9H.jpg","picUrlSmall":"http://pic3.40017.cn/scenery/destination/2015/04/17/22/pfbf9H_130x130_00.jpg"},{"picUrl":"http://pic3.40017.cn/scenery/destination/2015/06/18/11/c7fg3S.jpg","picUrlSmall":"http://pic3.40017.cn/scenery/destination/2015/06/18/11/c7fg3S_130x130_00.jpg"},{"picUrl":"http://pic3.40017.cn/scenery/destination/2015/04/18/15/xpJFOf.jpg","picUrlSmall":"http://pic3.40017.cn/scenery/destination/2015/04/18/15/xpJFOf_130x130_00.jpg"},{"picUrl":"http://pic3.40017.cn/scenery/destination/2015/04/18/15/r8YcI2.jpg","picUrlSmall":"http://pic3.40017.cn/scenery/destination/2015/04/18/15/r8YcI2_130x130_00.jpg"},{"picUrl":"http://pic3.40017.cn/scenery/destination/2015/04/18/15/QgFmNB.jpg","picUrlSmall":"http://pic3.40017.cn/scenery/destination/2015/04/18/15/QgFmNB_130x130_00.jpg"},{"picUrl":"http://pic3.40017.cn/scenery/destination/2015/04/18/15/EOu6b0.jpg","picUrlSmall":"http://pic3.40017.cn/scenery/destination/2015/04/18/15/EOu6b0_130x130_00.jpg"},{"picUrl":"http://pic3.40017.cn/scenery/destination/2015/04/18/15/MHaonB.jpg","picUrlSmall":"http://pic3.40017.cn/scenery/destination/2015/04/18/15/MHaonB_130x130_00.jpg"},{"picUrl":"http://pic3.40017.cn/scenery/destination/2015/04/18/15/znGGps.jpg","picUrlSmall":"http://pic3.40017.cn/scenery/destination/2015/04/18/15/znGGps_130x130_00.jpg"}]}],"currentPage":1,"allNum":1,"maxResult":20}}}
    • 格式化一下方便处理

      • 可以搜索JSON在线解析即可

        效果如图:

        这里写图片描述

      • 处理规则

        • 对象

          • 对象需要自己来创建一个类来对应,比如这一整个文本都是一个对象,我们自己创建一个类SearchEntity:

                public class SearchEntity {    private String showapi_res_code;    private String showapi_res_error;    public String getShowapi_res_code() {        return showapi_res_code;    }    public void setShowapi_res_code(String showapi_res_code) {        this.showapi_res_code = showapi_res_code;    }    public String getShowapi_res_error() {        return showapi_res_error;    }    public void setShowapi_res_error(String showapi_res_error) {        this.showapi_res_error = showapi_res_error;    }    public SearchBodyEntity getShowapi_res_body() {        return showapi_res_body;    }    public void setShowapi_res_body(SearchBodyEntity showapi_res_body) {        this.showapi_res_body = showapi_res_body;    }    SearchBodyEntity showapi_res_body;}

            可以看到:

            这里将对象中每一个数组、对象、键值对都以类、数组、String(这里可以是int等)显示出来。并且构造了get和set的方法

        • 数组

          其实数组只是存放对象的集合。所以直接声明List<对象>之后就可以直接调用数组

        • 键值对

          键值对就是一个自己声明的变量、类型根据后面的值来确定

      • 使用工具获得实体类以后的分析:

        • 工具生成实体类:
          这里写图片描述
        • 开始分析

          一般的工具类生成的开始的整个对象类为Root
          这里先进行文本的识别:

          SearchEntity entity;Class<SearchEntity> entityClass = SearchEntity.class;Gson gs = new Gson();entity= gs.fromJson(responseData,entityClass);

          然后就可以根据自己需要的获取文本中的数据:

              String code= entity.getShowapi_res_code();    SearchBodyEntity showapi_res_body = entity.getShowapi_res_body();    String retCode = showapi_res_body.getRet_code();    SearchBeanEntity pagebean = showapi_res_body.getPagebean();    Log.e("pagebean----",""+pagebean);    Log.e("pagebeangetAllPages----",""+pagebean.getAllPages());    Log.e("getContentList----",""+pagebean.getContentlist());    List<SearchListEntity> contentList = pagebean.getContentlist();    if (contentList.size() != 0) {        Log.e("contentList----", "" + contentList);        SearchListEntity[] contentlist_objects = new SearchListEntity[contentList.size()];        location[] locations = new location[contentList.size()];        String[] lons = new String[contentList.size()];        String[] lats = new String[contentList.size()];        String[] names = new String[contentList.size()];        String[] summarys = new String[contentList.size()];        String[] contents = new String[contentList.size()];        String[] attentions = new String[contentList.size()];        String[] opentimes = new String[contentList.size()];        String[] coupons = new String[contentList.size()];        String[] my_addresss = new String[contentList.size()];        String[] picture = new String[contentList.size()];        for (int i = 0; i < contentList.size(); i++) {            SearchListEntity contentlist_object = contentList.get(i);            contentlist_objects[i] = contentlist_object;            location location = contentlist_object.getLocation();            locations[i] = location;            String lon = location.getLon();            lons[i] = lon;            String lat = location.getLat();            lats[i] = lat;            String name = contentlist_object.getName();            names[i] = name;            String summary = contentlist_object.getSummary();            summarys[i] = summary;            String content = contentlist_object.getContent();            contents[i] = content;            String attention = contentlist_object.getAttention();            attentions[i] = attention;            String opentime = contentlist_object.getOpentime();            opentimes[i] = opentime;            String coupon = contentlist_object.getCoupon();            coupons[i] = coupon;            String my_address = contentlist_object.getAddress();            my_addresss[i] = my_address;            List<picList> picList = contentlist_object.getPicList();            picture[i] = picList.get(0).getPicUrl();            Log.e("", "" + picture[i]);        }

          这样以后:

          JSON文本中需要的内容就可以存储到安卓端对应的数组之中,可以通过数组进行显示以及在界面之间的传递。


最后,给出在本文中出现的实体类解析下载地址(没有积分的直接留邮箱就好):
http://download.csdn.net/detail/qq_34861102/9924780

以及整个项目的地址:https://github.com/Outliwer/Android-App

以及该部分代码所在位置:

这里写图片描述

阅读全文
1 0
原创粉丝点击