Android JSON解析

    1、JSON简介

        1)概念:
            JSON的全称是JavaScript Object Notation,是一种轻量级的数据交换格式。
        2)特点:
            (1)本质就是具有特定格式的字符串
            (2)JSON完全独立于编程语言
            (3)JSON比XML数据传输的有效性要高出很多。


    2、JSON数据格式

        1)整体结构
            String json1 = "{"id":12,"name":"Tom"}";
            String json2 = "[{"id":12,"name":"Tom"},{"id":12,"name":"Tom"}]";
        2)Json对象: {}
            (1)Json对象的结构: {key1:value1, key2:value2, key3:value3}
            (2)key的数据类型: 字符串
            (3)value的数据类型: 数值、字符串、null、json数组 []、json对象 {}
            (4)例子
                正确的:{“name”:”TOM”, “age”:12}
                错误的:{“aa”:“a”, 3}
        3)Json数组 :  [ ]
            (1)Json数组的结构: [value1, value2, value3]
            (2)value的数据类型: 数值、字符串、null、json数组 []、json对象 {}
            (3)例子
                正确的: [1, “ab”,[], {“n”:123, “b”:”abc”}]
                错误的: [1, “a”:3]


    3、JSON解析方向

        1)将java对象(包含集合)转换为json格式字符串 ---- 在服务器端应用
        2)将json格式字符串转换为java对象(包含集合)---- 在客户端应用


        3)Json和Java之间的转换关系
            JSON对应Java对象


            JSON数组和Java对象构成的list对应


        


    4、JSON解析技术

        1)Android原生技术:

            (1)特点:编程相对麻烦
            (2)数据之间转换
                (1)将json格式的字符串{}转换为Java对象
                    API:
                        JSONObject(String json) : 将json字符串解析为json对象
                        Xxx getXxx(String name) : 根据name, 在json对象中得到对应的Value
                        Xxx optXxx(String name) : 根据name, 在json对象中得到对应的Value

                        注意:
                            optXxx方法会在对应的key中的值不存在的时候返回一个空字符串或者返回你指定的默认值,但是getString方法会出现空指针异常的错误。
                    例子:

                ShopInfo shopInfo = null;
                //获取或创建json数据
                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";
                //解析json数据
                try {
                    JSONObject jsonObject = new JSONObject(json);
                    int id = jsonObject.optInt("id");
                    String name = jsonObject.optString("name");
                    Double price = jsonObject.optDouble("price");
                    String imagePath = jsonObject.optString("imagePath");
                    shopInfo = new ShopInfo(id,name,price,imagePath);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //显示数据
                tvNativeOrignal.setText(json);
                tvNativeLast.setText(shopInfo.toString());
public class ShopInfo {
    int id;
    String name;
    double price;
    String imagePath;

    public ShopInfo(int id, String name, double price, String imagePath) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.imagePath = imagePath;
    }

    @Override
    public String toString() {
        return "ShopInfo{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", price=" + price +
                ", imagePath='" + imagePath + '\'' +
                '}';

    }
}

                 (2)将json格式的字符串[]转换为Java对象的List
                    API:
                        JSONArray(String json) : 将json字符串解析为json数组
                        int length() : 得到json数组中元素的个数
                        Xxx getXxx(int index) : 根据下标得到json数组中对应的元素数据
                        Xxx optXxx(int index) : 根据下标得到json数组中对应的元素数据

                        注意:
                            optXxx方法会在对应的key中的值不存在的时候返回一个空字符串或者返回你指定的默认值,但是getString方法会出现空指针异常的错误。
                    例子:

                //获取或创建json数据
                List<ShopInfo> shopInfos = new ArrayList<>();
                String json2 = "[\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" +
                        "]";
                //解析json数据
                try {
                    JSONArray jsonArray = new JSONArray(json2);
                    for(int i = 0; i< jsonArray.length();i++){
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        int id = jsonObject.optInt("id");
                        String name = jsonObject.optString("name");
                        double price = jsonObject.optDouble("price");
                        String imagePath = jsonObject.optString("imagePath");
                        ShopInfo shopInfo1 = new ShopInfo(id,name,price,imagePath);
                        shopInfos.add(shopInfo1);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //显示数据
                tvNativeOrignal.setText(json2);
                tvNativeLast.setText(shopInfos.toString());


                (3)复杂json数据解析
                    a) 测试数据:


                    b) GsonFormat工具生成对象类
                        链接:https://pan.baidu.com/s/1YmHC0OlR4BmweBPMnLRsgw 提取码:3pfl 

                     c) 手动解析json数据

                //获取或创建json数据
                //封装
                DataInfo dataInfo = new DataInfo();
                String json3 = "{\n" +
                        "    \"data\": {\n" +
                        "        \"count\": 5,\n" +
                        "        \"items\": [\n" +
                        "            {\n" +
                        "                \"id\": 45,\n" +
                        "                \"title\": \"坚果\"\n" +
                        "            },\n" +
                        "            {\n" +
                        "                \"id\": 132,\n" +
                        "                \"title\": \"炒货\"\n" +
                        "            },\n" +
                        "            {\n" +
                        "                \"id\": 166,\n" +
                        "                \"title\": \"蜜饯\"\n" +
                        "            },\n" +
                        "            {\n" +
                        "                \"id\": 195,\n" +
                        "                \"title\": \"果脯\"\n" +
                        "            },\n" +
                        "            {\n" +
                        "                \"id\": 196,\n" +
                        "                \"title\": \"礼盒\"\n" +
                        "            }\n" +
                        "        ]\n" +
                        "    },\n" +
                        "    \"rs_code\": \"1000\",\n" +
                        "    \"rs_msg\": \"success\"\n" +
                        "}";
                //解析json数据
                try {
                    //解析
                    JSONObject jsonObject = new JSONObject(json3);
                    
                    //第一层解析
                    JSONObject data = jsonObject.optJSONObject("data");
                    String rs_code = jsonObject.optString("rs_code");
                    String rs_msg = jsonObject.optString("rs_msg");

                    //第一层封装
                    DataInfo.DataBean dataBean = new DataInfo.DataBean();
                    dataInfo.setData(dataBean);
                    dataInfo.setRs_code(rs_code);
                    dataInfo.setRs_msg(rs_msg);

                    //第二层解析
                    int count = jsonObject.optInt("count");
                    JSONArray items = data.getJSONArray("items");

                    //第二层封装
                    dataBean.setCount(count);
                    List <DataInfo.DataBean.ItemsBean> itemsBean = new ArrayList<DataInfo.DataBean.ItemsBean>();
                    dataBean.setItems(itemsBean);

                    //第三层解析
                    for(int i = 0;i < items.length();i++){
                        JSONObject jsonObject1 = items.getJSONObject(i);
                        int id = jsonObject1.optInt("id");
                        String title = jsonObject1.optString("title");

                        //第三层封装
                        DataInfo.DataBean.ItemsBean bean = new DataInfo.DataBean.ItemsBean();
                        bean.setId(id);
                        bean.setTitle(title);
                        itemsBean.add(bean);
                    }
                    
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                
                //显示数据
                tvNativeOrignal.setText(json3);
                tvNativeLast.setText(dataInfo.toString());


                (4)特殊json数据解析
                    a) 测试数据


                    b) 手动写解析json数据的对象类

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  class FilmBean {
    private String aid;

    @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;
    }

    private String author;
    private int coins;
    private String copyright;
    private String create;

}

                    c) 手动解析json数据

                //获取或创建json数据
                String json4 = "{\n" +
                        "    \"code\": 0,\n" +
                        "    \"list\": {\n" +
                        "        \"0\": {\n" +
                        "            \"aid\": \"6008965\",\n" +
                        "            \"author\": \"哔哩哔哩番剧\",\n" +
                        "            \"coins\": 170,\n" +
                        "            \"copyright\": \"Copy\",\n" +
                        "            \"create\": \"2016-08-25 21:34\"\n" +
                        "        },\n" +
                        "        \"1\": {\n" +
                        "            \"aid\": \"6008938\",\n" +
                        "            \"author\": \"哔哩哔哩番剧\",\n" +
                        "            \"coins\": 404,\n" +
                        "            \"copyright\": \"Copy\",\n" +
                        "            \"create\": \"2016-08-25 21:33\"\n" +
                        "        }\n" +
                        "    }\n" +
                        "}";

                //解析json数据

                //封装
                FilmInfo filmInfo = new FilmInfo();

                //第一层解析
                try {
                    JSONObject jsonObject = new JSONObject(json4);
                    int code  = jsonObject.optInt("code");
                    JSONObject list = jsonObject.getJSONObject("list");

                    //第一层封装
                    filmInfo.setCode(code);
                    List <FilmBean> filmBean = new ArrayList<>();
                    filmInfo.setList(filmBean);

                    //第二层解析
                    for(int i = 0;i < list.length();i++){
                        JSONObject jsonObject1 = list.getJSONObject(i+"");
                        String aid = jsonObject1.optString("aid");
                        String author = jsonObject1.optString("author");
                        int coins = jsonObject1.optInt("coins");
                        String copyright = jsonObject1.optString("copyright");
                        String create = jsonObject1.optString("create");

                        //第二层封装
                        FilmBean filmBean1 = new FilmBean();
                        filmBean1.setAid(aid);
                        filmBean1.setAuthor(author);
                        filmBean1.setCoins(coins);
                        filmBean1.setCopyright(copyright);
                        filmBean1.setCreate(create);

                        filmBean.add(filmBean1);

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //显示数据
                tvNativeOrignal.setText(json4);
                tvNativeLast.setText(filmInfo.toString());


        2)Gson框架技术
            (1)特点:
                编码简洁,谷歌官方推荐
            (2)下载地址:
                https://mvnrepository.com/artifact/com.google.code.gson/gson
            (3)数据之间转换
                (1)将json格式的字符串{}转换为Java对象
                    API:
                        fromJson(String json, Class<T> classOfT);
                        注意:
                            要求json对象中的key的名称与java对象对应的类中的属性名要相同
                    步骤
                        1)将Gson的jar包导入到项目中

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

                        2)创建Gson对象  :
                        3)通过创建的Gson对象调用fromJson()方法,返回该JSON数据对应的Java对象:

                //获取或创建json数据
                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";
                //解析json数据
                Gson gson = new Gson();
                ShopInfo shopInfo = gson.fromJson(json,ShopInfo.class);

                //显示数据
                tvGsonOrignal.setText(json);
                tvGsonLast.setText(shopInfo.toString());


                (2)将json格式的字符串[]转换为Java对象的List
                    API:
                        fromJson(String json, Type typeOfT);
                    步骤
                        1)将Gson的jar包导入到项目中
                        2)创建Gson对象  :
                        3)通过创建的Gson对象调用fromJson()方法,返回该JSON数据对应的Java集合:

                //获取或创建json数据
                String json2 = "[\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" +
                        "]";
                //解析json数据
                Gson gson2 = new Gson();
                List<ShopInfo> shopInfos = gson2.fromJson(json2, new TypeToken<List<ShopInfo>>(){}.getType());
                //显示数据
                tvGsonOrignal.setText(json2);
                tvGsonLast.setText(shopInfos.toString());

                (3)将Java对象转换为json字符串{}
                    API:
                        String toJson(Object src);
                    步骤
                        1)将Gson的jar包导入到项目中
                        2)创建Gson对象  :
                        3)通过创建的Gson对象调用toJson()方法,返回json数据:

                //获取或创建java对象
                ShopInfo shopInfo1 = new ShopInfo(3,"鲍鱼",250.0,"...");
                //生成json数据
                Gson gson3 = new Gson();
                String json3 = gson3.toJson(shopInfo1);
                //显示数据
                tvGsonOrignal.setText(shopInfo1.toString());
                tvGsonLast.setText(json3);

 

                (4)将Java对象的List转换为json字符串[]
                    API:
                        String toJson(Object src);
                    步骤
                        1)将Gson的jar包导入到项目中
                        2)创建Gson对象  :
                        3)通过创建的Gson对象调用toJson()方法,返回json数据:

                //获取或创建java对象
                List<ShopInfo> shops = new ArrayList<>();
                ShopInfo baoyu = new ShopInfo(3,"鲍鱼",250.0,"...");
                ShopInfo longxia = new ShopInfo(4,"龙虾",220.0,"!!!");
                shops.add(baoyu);
                shops.add(longxia);
                //生成json数据
                Gson gson4 = new Gson();
                String json4 = gson4.toJson(shops);
                //显示数据
                tvGsonOrignal.setText(shops.toString());
                tvGsonLast.setText(json4);


        3)FastJson框架技术
            (1)特点:
                Fastjson是一个Java语言编写的高性能功能完善的JSON库。它采用一种“假定有序快速匹配”的算法,把JSON Parse的性能提升到极致,是目前Java语言中最快的JSON库。
            (2)下载地址:
                https://github.com/alibaba/fastjson/wiki
            (3)数据之间转换
                (1)将json格式的字符串{}转换为Java对象
                    API:
                        parseObject(String json, Class<T> classOfT);
                    步骤:
                        1)导入fastjson的jar包

compile 'com.alibaba:fastjson:1.2.57'

                        2)JSON调用parseObject()方法,获取转换后的Java对象

                //获取或创建json数据
                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";
                //解析json数据
                ShopInfo shopInfo = JSON.parseObject(json,ShopInfo.class);
                //显示数据
                tvFastjsonOrignal.setText(json);
                tvFastjsonLast.setText(shopInfo.toString());

注意:在反序列化的时候会先用无参的构造方法构造一个类实例。所以在ShopInfo类里面要有一个无参数的构造方法。
不然会报一下错误:


                (2)将json格式的字符串[]转换为Java对象的List
                    API:
                        List<T> parseArray(String json,Class<T> classOfT);
                    步骤:
                        1)导入fastjson的jar包
                        2)JSON调用parseArray()方法,获取转换后的Java集合

                //获取或创建json数据
                String json2 = "[\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" +
                        "]";
                //解析json数据
                List<ShopInfo> shopInfos = JSON.parseArray(json2,ShopInfo.class);
                //显示数据
                tvFastjsonOrignal.setText(json2);
                tvFastjsonLast.setText(shopInfos.toString());


                (3)将Java对象转换为json字符串{}
                    API:
                        String toJSONString(Object object);
                    步骤:
                        1)导入fastjson的jar包
                        2)JSON调用toJSONString()方法,获取转换后的json数据

                //创建一个java对象
                ShopInfo shopInfo1 = new ShopInfo(1,"baoyu",250.0,"111");
                //生成json数据
                String json3 = JSON.toJSONString(shopInfo1);
                //显示数据
                tvFastjsonOrignal.setText(shopInfo1.toString());
                tvFastjsonLast.setText(json3);


                (4)将Java对象的List转换为json字符串[]
                    API:
                        String toJSONString(Object object);
                    步骤:
                        1)导入fastjson的jar包
                        2)JSON调用toJSONString()方法,获取转换后的json数据

                //创建一个java对象
                List<ShopInfo> shops = new ArrayList<>();
                ShopInfo shopInfo3 = new ShopInfo(3,"baoyu",250.0,"333");
                ShopInfo shopInfo4 = new ShopInfo(4,"daxia",270.0,"444");
                shops.add(shopInfo3);
                shops.add(shopInfo4);
                //生成json数据
                String json5 = JSON.toJSONString(shops);
                //显示数据
                tvFastjsonOrignal.setText(shops.toString());
                tvFastjsonLast.setText(json5);

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值