Android框架之路——Json解析一篇就够(原生技术+Gson+FastJson)

一、简介:

JSON(JavaScript Object Notation, JS 对象标记) 是一种轻量级的数据交换格式。它基于 ECMAScript 规范的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。

基本写一个涉及网络请求数据的App都要去解析Json数据。xml方式效率不如Json来的高,所以首选还是Json。本文将分别进行原生技术手动解析、使用Gson和FastJson三种方法来解析Json数据。

Gson是Google提供的一种解析json数据的框架,编码简洁,官方推荐。Fastjson是一个Java语言编写的高性能功能完善的JSON库,它采用一种“假定有序快速匹配”的算法,把JSON Parse的性能提升到极致,是目前Java语言中最快的JSON库。

二、Json数组与对象区分:

很简单,遇到{…}就是Json对象,遇到[…]就是Json数组。

三、Demo效果:

  1. 原生技术手动解析
                                这里写图片描述
  2. Gson框架解析
                                这里写图片描述
  3. FastJson框架解析
                                这里写图片描述

四、解锁所有姿势:

无论是Json数组还是Json对象,都是字符串,均可以转成JavaBean或者JavaBean的List集合。

  1. 原生技术手动解析

    • 将json对象转换成JavaBean

      1. Api介绍(org.json包下)

        JSONObject(String string) : 构造函数,将json字符串解析为json对象.
        int length() : 得到json对象的长度.
        Xxx getXxx(String name) : 根据name获取json对象中对应的value,不存在时造成空指针异常.
        Xxx optXxx(String name) : 根据name获取json对象中对应的value,不存在时返回""或默认值.
        
      2. 测试json数据

        {
            "status": "0",
            "msg": "ok",
            "result": "哈哈啊哈哈哈哈"
        }
        
      3. 实现解析

        private void jsonToJavaBeanByNative() {
            String json = "{\n" +
                    "    \"status\": \"0\",\n" +
                    "    \"msg\": \"ok\",\n" +
                    "    \"result\": \"哈哈啊哈哈哈哈\"\n" +
                    "}";
            //解析
            try {
                JSONObject jsonObject = new JSONObject(json);
                String status = jsonObject.getString("status");
                String result = jsonObject.optString("result");
                String msg = jsonObject.optString("msg");
        
                tv1.setText(json);
                tv2.setText(new DemoBean(status, msg, result).toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        
    • 将json数组转换成JavaBean的List集合

      1. Api介绍(org.json包下)

        JSONArray(String string) : 构造函数,将json字符串解析为json数组.
        int length() : 得到json数组的长度.
        Xxx getXxx(String name) : 根据name获取json数组中对应的value,不存在时造成空指针异常.
        Xxx optXxx(String name) : 根据name获取json数组中对应的value,不存在时返回""或默认值.
        
      2. 测试json数据

        [
            {
                "status": "0",
                "msg": "ok",
                "result": "哈哈啊哈哈哈哈"
            },
            {
                "status": "1",
                "msg": "Error",
                "result": "空的"
            }
        ]
        
      3. 实现解析

        private void jsonToJavaBeanListByNative() {
            String json = "[\n" +
                    "    {\n" +
                    "        \"status\": \"0\",\n" +
                    "        \"msg\": \"ok\",\n" +
                    "        \"result\": \"哈哈啊哈哈哈哈\"\n" +
                    "    },\n" +
                    "    {\n" +
                    "        \"status\": \"1\",\n" +
                    "        \"msg\": \"Error\",\n" +
                    "        \"result\": \"空的\"\n" +
                    "    }\n" +
                    "]";
        
            List<DemoBean> list = new ArrayList<>();
            try {
                JSONArray jsonArray = new JSONArray(json);
        
                for (int i = 0; i < jsonArray.length(); i++){
                    JSONObject obj = jsonArray.getJSONObject(i);
        
                    if(obj != null){
                        String status = obj.getString("status");
                        String result = obj.optString("result");
                        String msg = obj.optString("msg");
        
                        list.add(new DemoBean(status, msg, result));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        
            tv1.setText(json);
            tv2.setText(list.toString());
        }
        
    • 复杂json数据解析

      1. 测试json数据

        {
            "status": "0",
            "msg": "ok",
            "result": {
                "total": "33731",
                "pagenum": "1",
                "pagesize": "1",
                "list": [
                    {
                        "content": "文化交流请问如何气温哦日哦还欠我I偶然穷温家穷文件哦I你去我就饿哦老婆群文件欧赔",
                        "addtime": "2014-10-14 15:48:18",
                        "url": "http://m.kaixinhui.com/detail-26458.html"
                    },
                    {
                        "content": "可是到了好看你看我哪舍得回来可完全认可啊你说的卡就好了啊深刻的理解好看啦可能去问价钱",
                        "addtime": "2014-10-14 15:48:18",
                        "url": "http://m.kaixinhui.com/detail-26458.html"
                    }
                ]
            }
        }
        
      2. 使用GsonFormat生成JavaBean
        • File—>Settings—>Plugins—>搜索GsonFormat插件—>安装
      3. 实现解析

        private void parseComplexJson() {
            String json = "{\n" +
                    "    \"status\": \"0\",\n" +
                    "    \"msg\": \"ok\",\n" +
                    "    \"result\": {\n" +
                    "        \"total\": \"33731\",\n" +
                    "        \"pagenum\": \"1\",\n" +
                    "        \"pagesize\": \"1\",\n" +
                    "        \"list\": [\n" +
                    "            {\n" +
                    "                \"content\": \"文化交流请问如何气温哦日哦还欠我I偶然穷温家穷文件哦I你去我就饿哦老婆群文件欧赔\",\n" +
                    "                \"addtime\": \"2014-10-14 15:48:18\",\n" +
                    "                \"url\": \"http://m.kaixinhui.com/detail-26458.html\"\n" +
                    "            },\n" +
                    "            {\n" +
                    "                \"content\": \"可是到了好看你看我哪舍得回来可完全认可啊你说的卡就好了啊深刻的理解好看啦可能去问价钱\",\n" +
                    "                \"addtime\": \"2014-10-14 15:48:18\",\n" +
                    "                \"url\": \"http://m.kaixinhui.com/detail-26458.html\"\n" +
                    "            }\n" +
                    "        ]\n" +
                    "    }\n" +
                    "}";
        
            ComplexDemoBean complexDemoBean = new ComplexDemoBean();
        
            try {
                JSONObject jsonObject = new JSONObject(json);
                complexDemoBean.setStatus(jsonObject.optString("status"));
                complexDemoBean.setMsg(jsonObject.optString("msg"));
                JSONObject object = jsonObject.optJSONObject("result");
        
                ComplexDemoBean.ResultBean resultBean = new ComplexDemoBean.ResultBean();
                resultBean.setTotal(object.optString("total"));
                resultBean.setPagenum(object.optString("pagenum"));
                resultBean.setPagesize(object.optString("pagesize"));
                JSONArray list = object.getJSONArray("list");
        
                List<ComplexDemoBean.ResultBean.ListBean> beanList = new ArrayList<>();
                for (int i = 0; i < list.length(); i++){
                    ComplexDemoBean.ResultBean.ListBean listBean = new ComplexDemoBean.ResultBean.ListBean();
                    JSONObject obj = list.getJSONObject(i);
                    listBean.setContent(obj.optString("content"));
                    listBean.setAddtime(obj.optString("addtime"));
                    listBean.setUrl(obj.optString("url"));
                    beanList.add(listBean);
                }
        
                resultBean.setList(beanList);
                complexDemoBean.setResult(resultBean);
        
                tv1.setText(json);
                tv2.setText(complexDemoBean.toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        
    • 特殊json数据解析

      有些数据他们的key为数字,使用GsonFormat插件生成JavaBean是有问题的,这时需要我们自己去手写Bean。

      1. 示例Json

        {
            "code": 0,
            "list": {
                "0": {
                    "aid": "9698756",
                    "author": "哔哩哔哩番剧",
                    "copyright": "Copy",
                    "create": "2017-04-08 18:39",
                    "coins": 22043
                },
                "1": {
                    "aid": "9854952",
                    "author": "哔哩哔哩番剧",
                    "copyright": "Copy",
                    "create": "2017-04-15 15:29",
                    "coins": 16991
                }
            }
        }
        
      2. 自定义JavaBean

        public class FilmInfo {
        
            private int code;
            private List<FilmBean> list;
        
            @Override
            public String toString() {
                return "FilmInfo{" +
                        "code=" + code +
                        ", list=" + list +
                        '}';
            }
        
            public int getCode() {
                return code;
            }
        
            public void setCode(int code) {
                this.code = code;
            }
        
            public List<FilmBean> getList() {
                return list;
            }
        
            public void setList(List<FilmBean> list) {
                this.list = list;
            }
        
            public static class FilmBean{
                private String aid;
                private String author;
                private int coins;
                private String copyright;
                private String create;
        
                @Override
                public String toString() {
                    return "FilmBean{" +
                            "aid='" + aid + '\'' +
                            ", author='" + author + '\'' +
                            ", coins=" + coins +
                            ", copyright='" + copyright + '\'' +
                            ", create='" + create + '\'' +
                            '}';
                }
        
                public String getAid() {
                    return aid;
                }
        
                public void setAid(String aid) {
                    this.aid = aid;
                }
        
                public String getAuthor() {
                    return author;
                }
        
                public void setAuthor(String author) {
                    this.author = author;
                }
        
                public int getCoins() {
                    return coins;
                }
        
                public void setCoins(int coins) {
                    this.coins = coins;
                }
        
                public String getCopyright() {
                    return copyright;
                }
        
                public void setCopyright(String copyright) {
                    this.copyright = copyright;
                }
        
                public String getCreate() {
                    return create;
                }
        
                public void setCreate(String create) {
                    this.create = create;
                }
            }
        }
        
      3. 实现解析

        private void specialJsonParse() {
            String json = "{\n" +
                    "    \"code\": 0,\n" +
                    "    \"list\": {\n" +
                    "        \"0\": {\n" +
                    "            \"aid\": \"9698756\",\n" +
                    "            \"author\": \"哔哩哔哩番剧\",\n" +
                    "            \"copyright\": \"Copy\",\n" +
                    "            \"create\": \"2017-04-08 18:39\",\n" +
                    "            \"coins\": 22043\n" +
                    "        },\n" +
                    "        \"1\": {\n" +
                    "            \"aid\": \"9854952\",\n" +
                    "            \"author\": \"哔哩哔哩番剧\",\n" +
                    "            \"copyright\": \"Copy\",\n" +
                    "            \"create\": \"2017-04-15 15:29\",\n" +
                    "            \"coins\": 16991\n" +
                    "        }\n" +
                    "    }\n" +
                    "}";
            FilmInfo filmInfo = new FilmInfo();
        
            try {
                JSONObject jsonObject = new JSONObject(json);
                filmInfo.setCode(jsonObject.optInt("code"));
        
                List<FilmInfo.FilmBean> list = new ArrayList<>();
                JSONObject object = jsonObject.optJSONObject("list");
        
                for(int i = 0; i < object.length(); i++){
                    FilmInfo.FilmBean filmBean = new FilmInfo.FilmBean();
                    filmBean.setAid(object.getJSONObject(i+"").getString("aid"));
                    filmBean.setAuthor(object.getJSONObject(i+"").getString("author"));
                    filmBean.setCopyright(object.getJSONObject(i+"").getString("copyright"));
                    filmBean.setCreate(object.getJSONObject(i+"").getString("create"));
                    filmBean.setCoins(object.getJSONObject(i+"").getInt("coins"));
        
                    list.add(filmBean);
                }
        
                filmInfo.setList(list);
        
                tv1.setText(json);
                tv2.setText(filmInfo.toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        
  2. Gson框架解析

    • 将json对象字符串转换为javaBean

      1. Api介绍(compile ‘com.google.code.gson:gson:2.8.0’)

        fromJson(String json, Class<T> classOfT);  //要求json对象中的key的名称与java对象对应的类中的属性名要相同
        
      2. json数据示例

        {
            "id":2, "name":"大虾", 
            "price":12.3, 
            "imagePath":"http://192.168.10.165:8080/L05_Server/images/f1.jpg"
        }
        
      3. 实现解析

        private void jsonToJavaBeanByGson() {
            String json = "{\n" +
                    "\t\"id\":2, \"name\":\"大虾\", \n" +
                    "\t\"price\":12.3, \n" +
                    "\t\"imagePath\":\"http://192.168.10.165:8080/L05_Server/images/f1.jpg\"\n" +
                    "}\n";
            Gson gson = new Gson();
            ShopBean shopBean = gson.fromJson(json, ShopBean.class);
            tv1.setText(json);
            tv2.setText(shopBean.toString());
        }
        
    • 将json数组字符串转换成javaBean的List集合

      1. Api介绍

        fromJson(String json, Type typeOfT);     
        //第二个参数传递Type类型 e.g. new TypeToken<List<ShopBean>>(){}.getType()
        
      2. json数据示例

        [
            {
                "id": 1,
                "imagePath": "http://192.168.10.165:8080/f1.jpg",
                "name": "大虾1",
                "price": 12.3
            },
            {
                "id": 2,
                "imagePath": "http://192.168.10.165:8080/f2.jpg",
                "name": "大虾2",
                "price": 12.5
            }
        ]
        
      3. 实现解析

        private void jsonToJavaBeanListByGson() {
            String json = "[\n" +
                    "    {\n" +
                    "        \"id\": 1,\n" +
                    "        \"imagePath\": \"http://192.168.10.165:8080/f1.jpg\",\n" +
                    "        \"name\": \"大虾1\",\n" +
                    "        \"price\": 12.3\n" +
                    "    },\n" +
                    "    {\n" +
                    "        \"id\": 2,\n" +
                    "        \"imagePath\": \"http://192.168.10.165:8080/f2.jpg\",\n" +
                    "        \"name\": \"大虾2\",\n" +
                    "        \"price\": 12.5\n" +
                    "    }\n" +
                    "]";
            Gson gson = new Gson();
            List<ShopBean> list = gson.fromJson(json, new TypeToken<List<ShopBean>>(){}.getType());
        
            tv1.setText(json);
            tv2.setText(list.toString());
        }
        
    • 将java对象转换为json字符串

      1. Api介绍

        String toJson(Object src);
        
      2. 实现转换

        private void javaBeanToJsonByGson() {
            DemoBean demoBean = new DemoBean("0", "haha", "是你答复我还是额咯结尾");
            Gson gson = new Gson();
            String json = gson.toJson(demoBean);
            tv1.setText(demoBean.toString());
            tv2.setText(json);
        }
        
    • 将javaBean的集合对象转换成json数组

      1. Api介绍

        String toJson(Object src);
        
      2. 实现转换

        private void javaBeanListToJsonByGson() {
            List<ShopBean> list = new ArrayList<>();
            ShopBean shopBean1 = new ShopBean("http://www.baidu.com", 12.3, "鱼肉", 1);
            ShopBean shopBean2 = new ShopBean("http://www.baidu.com", 15.7, "鸡腿", 2);
            list.add(shopBean1);
            list.add(shopBean2);
        
            Gson gson = new Gson();
            String json = gson.toJson(list);
            tv1.setText(list.toString());
            tv2.setText(json);
        }
        
  3. FastJson框架解析

    • 将json对象字符串转换为javaBean

      1. Api介绍(compile ‘com.alibaba:fastjson:1.2.31’)

        Json.parseObject(String json, Class<T> classOfT);
        
      2. 实现解析

         private void javaBeanListToJsonByFastJson() {
            String json = "{\n" +
                    "\t\"id\":2, \"name\":\"大虾\", \n" +
                    "\t\"price\":12.3, \n" +
                    "\t\"imagePath\":\"http://192.168.10.165:8080/L05_Server/images/f1.jpg\"\n" +
                    "}\n";
            ShopBean shopBean = JSON.parseObject(json, ShopBean.class);
        
            tv1.setText(json);
            tv2.setText(shopBean.toString());
        }
        
    • 将json数组字符串转换成javaBean的List集合

      1. Api介绍

        Json.List<T> parseArray(String json,Class<T> classOfT);
        
      2. 实现解析

         private void javaBeanListToJsonByFastJson() {
            String json = "{\n" +
                    "\t\"id\":2, \"name\":\"大虾\", \n" +
                    "\t\"price\":12.3, \n" +
                    "\t\"imagePath\":\"http://192.168.10.165:8080/L05_Server/images/f1.jpg\"\n" +
                    "}\n";
            ShopBean shopBean = JSON.parseObject(json, ShopBean.class);
        
            tv1.setText(json);
            tv2.setText(shopBean.toString());
        }
        
    • 将java对象转换为json字符串

      1. Api介绍

        String Json.toJSONString(Object object);
        
      2. 实现解析

        private void javaBeanToJsonByFastJson() {
            DemoBean demoBean = new DemoBean("0", "haha", "是你答复我还是额咯结尾");
            String jsonString = JSON.toJSONString(demoBean);
            tv1.setText(demoBean.toString());
            tv2.setText(jsonString);
        }
        
    • 将javaBean的集合对象转换成json数组

      1. Api介绍

        String Json.toJSONString(Object object);
        
      2. 实现解析

        private void javaBeanListToJsonByFastJson() {
            List<ShopBean> list = new ArrayList<>();
            ShopBean shopBean1 = new ShopBean("http://www.baidu.com", 12.3, "鱼肉", 1);
            ShopBean shopBean2 = new ShopBean("http://www.baidu.com", 15.7, "鸡腿", 2);
            list.add(shopBean1);
            list.add(shopBean2);
        
            String jsonString = JSON.toJSONString(list);
            tv1.setText(list.toString());
            tv2.setText(jsonString);
        }
        

五、Demo下载:

       源码链接


个人公众号:每日推荐一篇技术博客,坚持每日进步一丢丢…欢迎关注,想建个微信群,主要讨论安卓和Java语言,一起打基础、用框架、学设计模式,菜鸡变菜鸟,菜鸟再起飞,愿意一起努力的话可以公众号留言,谢谢…

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页