Android - 手动解析Json数据(学习笔记一)

腾讯课堂 —> 尚硅谷Android视频《JSON解析》

在这里插入图片描述

在这里插入图片描述

布局

  • activity_main.xml
 	<Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/bt1"
        android:text="json格式的字符串转Java对象"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/bt2"
        android:text="json格式的字符串转Java对象的list"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/bt3"
        android:text="复杂json数据解析"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/bt4"
        android:text="特殊json数据解析"/>



    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">


        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">


            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="显示原始数据"
                android:textColor="@color/colorAccent"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/tvJson"/>


            <View
                android:layout_width="match_parent"
                android:layout_height="1.5dp"
                android:background="#A9A9A9"/>


            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="解析后的数据"
                android:textColor="@color/colorAccent"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/tvJava"/>


        </LinearLayout>
    </ScrollView>

在这里插入图片描述

先行准备

1. 创建一个ShopInfo.java(快捷键:Alt+Insert)

/**
 * User: hu
 * Date: 2020/9/3
 * title: 商店的实体类
 */
public class ShopInfo {
    private int id;
    private String name;
    private double price;
    private String imagePath;

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

    public ShopInfo() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getImagePath() {
        return imagePath;
    }

    public void setImagePath(String imagePath) {
        this.imagePath = imagePath;
    }

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

2. 创建一个DataInfo.java(安装插件GsonFormat)

Android Studio 安装插件GsonFormat (Json数据转换实体类)

import java.util.List;

/**
 * User: hu
 * Date: 2020/9/3
 * title: DataInfo实体类
 */
public class DataInfo {

    /**
     * data : {"count":5,"items":[{"id":45,"title":"小麦","titile":"大米"},{"id":134,"titile":"大米"},{"id":115,"title":"小米"},{"id":15,"title":"苹果"},{"id":68,"title":"三只松鼠"}]}
     * rs_code : 1000
     * rs_msg : success
     */

    private DataBean data;
    private String rs_code;
    private String rs_msg;

    @Override
    public String toString() {
        return "DataInfo{" +
                "\ndata=" + data +
                ", \nrs_code='" + rs_code + '\'' +
                ", \nrs_msg='" + rs_msg + '\'' +
                '}';
    }

    public DataBean getData() {
        return data;
    }

    public void setData(DataBean data) {
        this.data = data;
    }

    public String getRs_code() {
        return rs_code;
    }

    public void setRs_code(String rs_code) {
        this.rs_code = rs_code;
    }

    public String getRs_msg() {
        return rs_msg;
    }

    public void setRs_msg(String rs_msg) {
        this.rs_msg = rs_msg;
    }

    public static class DataBean {
        /**
         * count : 5
         * items : [{"id":45,"title":"小麦"},{"id":134,"titile":"大米"},{"id":115,"title":"小米"},{"id":15,"title":"苹果"},{"id":68,"title":"三只松鼠"}]
         */

        private int count;
        private List<ItemsBean> items;

        @Override
        public String toString() {
            return "DataBean{" +
                    "\ncount=" + count +
                    ", \nitems=" + items +
                    '}';
        }

        public int getCount() {
            return count;
        }

        public void setCount(int count) {
            this.count = count;
        }

        public List<ItemsBean> getItems() {
            return items;
        }

        public void setItems(List<ItemsBean> items) {
            this.items = items;
        }

        public static class ItemsBean {
            /**
             * id : 45
             * title : 小麦
             * titile : 大米
             */


            private int id;
            private String title;
            private String titile;

            @Override
            public String toString() {
                return "\n\tItemsBean{" +
                        "id=" + id +
                        ", title='" + title + '\'' +
                        '}';
            }

            public int getId() {
                return id;
            }

            public void setId(int id) {
                this.id = id;
            }

            public String getTitle() {
                return title;
            }

            public void setTitle(String title) {
                this.title = title;
            }

            public String getTitile() {
                return titile;
            }

            public void setTitile(String titile) {
                this.titile = titile;
            }
        }
    }
}

3. 创建一个FilmInfo.java

import java.util.List;
/**
 * User: hu
 * Time: 19:59
 * title:
 */
public class FilmInfo {
    private int code;
    private List<FilmBean> list;

    @Override
    public String toString() {
        return "FilmInfo{" +
                "\ncode=" + code +
                ", \nlist=" + 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 "\n\tFilmBean{" +
                    "\n\t\taid='" + aid + '\'' +
                    ", \n\t\tauthor='" + author + '\'' +
                    ", \n\t\tcoins=" + coins +
                    ", \n\t\tcopyright='" + copyright + '\'' +
                    ", \n\t\tcreate='" + 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;
        }
    }
}

在这里插入图片描述

一、json格式的字符串转Java对象

  • Json数据
{
	"id":2,"name":"小米煎饼",
	"price":11.2,
	"imagePath":"https://pics3.baidu.com/feed/960a304e251f95caf3db58a3973c4639670952af.jpeg?token=6d173c37740f4bcd401c8c44632b87d6"
}
  • MainActivity.java
		//json格式的字符串转Java对象
        bt1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jsonToJavaObjectByNative();
            }
        });
	//json格式的字符串转Java对象
    private void jsonToJavaObjectByNative(){
        //获取或创建json数据
        String json = "{\n" +
                "\t\"id\":2,\"name\":\"小米煎饼\",\n" +
                "\t\"price\":11.2,\n" +
                "\t\"imagePath\":\"https://pics3.baidu.com/feed/960a304e251f95caf3db58a3973c4639670952af.jpeg?token=6d173c37740f4bcd401c8c44632b87d6\"\n" +
                "}";

        //解析json
        JSONObject jsonObject = null;
        ShopInfo shopInfo = null;
        try {
            jsonObject = new JSONObject(json);
            int id1 = jsonObject.getInt("id"); //方法一:这个有可能出现空指针异常
            int id2 = jsonObject.optInt("id"); //方法二:推荐使用这个方法
            String name = jsonObject.optString("name");
            double price = jsonObject.optDouble("price");
            String imagePath = jsonObject.optString("imagePath");


            shopInfo = new ShopInfo(id2, name, price, imagePath);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        //显示Json数据
        tvJson.setText(json);
        tvJava.setText(shopInfo.toString());
    }
  • 实现图
    在这里插入图片描述

在这里插入图片描述

二、json格式的字符串转Java对象的list

  • Json数据
[
	{
		"id":1,"name":"小米煎饼",
		"price":11.2,
		"imagePath":"https://pics3.baidu.com/feed/960a304e251f95caf3db58a3973c4639670952af.jpeg?token=6d173c37740f4bcd401c8c44632b87d6"
	},
	{
		"id":2,"name":"芒果干",
		"price":10.2,
		"imagePath":"https://pics3.baidu.com/feed/960a304e251f95caf3db58a3973c4639670952af.jpeg?token=6d173c37740f4bcd401c8c44632b87d6"
	}
]
  • MainActivity.java
		//json格式的字符串转Java对象的list
        bt2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jsonToJavaListByNative();
            }
        });
	//json格式的字符串转Java对象的list
    private void jsonToJavaListByNative() {
        //获取或创建json数据
        String json = "[\n" +
                "\t{\n" +
                "\t\t\"id\":1,\"name\":\"小米煎饼\",\n" +
                "\t\t\"price\":11.2,\n" +
                "\t\t\"imagePath\":\"https://pics3.baidu.com/feed/960a304e251f95caf3db58a3973c4639670952af.jpeg?token=6d173c37740f4bcd401c8c44632b87d6\"\n" +
                "\t},\n" +
                "\t{\n" +
                "\t\t\"id\":2,\"name\":\"芒果干\",\n" +
                "\t\t\"price\":10.2,\n" +
                "\t\t\"imagePath\":\"https://pics3.baidu.com/feed/960a304e251f95caf3db58a3973c4639670952af.jpeg?token=6d173c37740f4bcd401c8c44632b87d6\"\n" +
                "\t}\n" +
                "]";

        List<ShopInfo> shops = new ArrayList<>();
        //解析json
        try {
            JSONArray jsonArray = new JSONArray(json);

            for (int i = 0; i < jsonArray.length(); i++){
                JSONObject jsonObject = jsonArray.getJSONObject(i);

                //避免空指针异常
                if (jsonObject != null){
                    int id = jsonObject.getInt("id");
                    String name = jsonObject.optString("name");
                    double price = jsonObject.optDouble("price");
                    String imagePath = jsonObject.optString("imagePath");

                    //封装Java对象
                    ShopInfo shopInfo = new ShopInfo(id, name, price, imagePath);
                    shops.add(shopInfo);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        //显示Json数据
        tvJson.setText(json);
        tvJava.setText(shops.toString());
    }
  • 实现图
    在这里插入图片描述

在这里插入图片描述

三、复杂json数据解析

  • Json数据
{
	"data":{
		"count":5,
		"items":[
			{
				"id":45,
				"title":"小麦"
			},
			{
				"id":134,
				"title":"大米"
			},
			{
				"id":115,
				"title":"小米"
			},
			{
				"id":15,
				"title":"苹果"
			},
			{
				"id":68,
				"title":"三只松鼠"
			}
		]
	},
	"rs_code":"1000",
	"rs_msg":"success"
}
  • MainActivity.java
		//复杂json数据解析
        bt3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jsonToJavaOfComplex();
            }
        });
	//复杂json数据解析
    private void jsonToJavaOfComplex() {
        //获取或创建json数据
        String json = "{\n" +
                "\t\"data\":{\n" +
                "\t\t\"count\":5,\n" +
                "\t\t\"items\":[\n" +
                "\t\t\t{\n" +
                "\t\t\t\t\"id\":45,\n" +
                "\t\t\t\t\"title\":\"小麦\"\n" +
                "\t\t\t},\n" +
                "\t\t\t{\n" +
                "\t\t\t\t\"id\":134,\n" +
                "\t\t\t\t\"titile\":\"大米\"\n" +
                "\t\t\t},\n" +
                "\t\t\t{\n" +
                "\t\t\t\t\"id\":115,\n" +
                "\t\t\t\t\"title\":\"小米\"\n" +
                "\t\t\t},\n" +
                "\t\t\t{\n" +
                "\t\t\t\t\"id\":15,\n" +
                "\t\t\t\t\"title\":\"苹果\"\n" +
                "\t\t\t},\n" +
                "\t\t\t{\n" +
                "\t\t\t\t\"id\":68,\n" +
                "\t\t\t\t\"title\":\"三只松鼠\"\n" +
                "\t\t\t}\n" +
                "\t\t]\n" +
                "\t},\n" +
                "\t\"rs_code\":\"1000\",\n" +
                "\t\"rs_msg\":\"success\"\n" +
                "}";

        //封装Java对象
        DataInfo dataInfo = new DataInfo();

        //解析json
        try {
            JSONObject jsonObject = new JSONObject(json);

            //第一层解析
            JSONObject data = jsonObject.optJSONObject("data");
            String rs_code = jsonObject.optString("rs_code");
            String rs_msg = jsonObject.optString("rs_msg");
            //第一层封装
            dataInfo.setRs_code(rs_code);
            dataInfo.setRs_msg(rs_msg);
            DataInfo.DataBean dataBean = new DataInfo.DataBean();
            dataInfo.setData(dataBean);

            //第二层解析
            int count = data.optInt("count");
            JSONArray items = data.getJSONArray("items");
            //第二层封装
            dataBean.setCount(count);
            List<DataInfo.DataBean.ItemsBean> itemsBean = new ArrayList<>();
            dataBean.setItems(itemsBean);

            //第三层解析
            for (int i = 0; i < items.length(); i++){
                JSONObject jsonObject1 = items.optJSONObject(i);
                if (jsonObject1 != null){
                    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();
        }


        //显示Json数据
        tvJson.setText(json);
        tvJava.setText(dataInfo.toString());
    }
  • 实现图
    在这里插入图片描述

在这里插入图片描述

四、特殊json数据解析

  • json数据
{
	"code":0,
	"list":{
		"0":{
			"aid":"6008965",
			"author":"滴滴滴",
			"coins":170,
			"copyright":"Copy",
			"create":"2020-09-25 19:25"
		},
		"1":{			
			"aid":"12532654",
			"author":"啧啧啧",
			"coins":404,
			"copyright":"Copy",
			"create":"2020-09-26 20:25"
		}
	}
}
		//特殊json数据解析
        bt4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jsonToJavaOfSpecial();
            }
        });
	//特殊json数据解析
    private void jsonToJavaOfSpecial() {
        //获取或创建json数据
        String json = "{\n" +
                "\t\"code\":0,\n" +
                "\t\"list\":{\n" +
                "\t\t\"0\":{\n" +
                "\t\t\t\"aid\":\"6008965\",\n" +
                "\t\t\t\"author\":\"滴滴滴\",\n" +
                "\t\t\t\"coins\":170,\n" +
                "\t\t\t\"copyright\":\"Copy\",\n" +
                "\t\t\t\"create\":\"2020-09-25 19:25\"\n" +
                "\t\t},\n" +
                "\t\t\"1\":{\t\t\t\n" +
                "\t\t\t\"aid\":\"12532654\",\n" +
                "\t\t\t\"author\":\"啧啧啧\",\n" +
                "\t\t\t\"coins\":404,\n" +
                "\t\t\t\"copyright\":\"Copy\",\n" +
                "\t\t\t\"create\":\"2020-09-26 20:25\"\n" +
                "\t\t}\n" +
                "\t}\n" +
                "}";

        //创建封装java对象
        FilmInfo filmInfo = new FilmInfo();

        //解析json
        try {
            JSONObject jsonObject = new JSONObject(json);

            //第一层解析
            int code = jsonObject.optInt("code");
            JSONObject list = jsonObject.optJSONObject("list");
            //第一层封装
            filmInfo.setCode(code);
            List<FilmInfo.FilmBean> lists = new ArrayList<>();
            filmInfo.setList(lists);

            //第二层解析
            for (int i = 0; i < list.length(); i++){
                JSONObject jsonObject1 = list.optJSONObject(i + "");
                if (jsonObject1 != null){
                    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");
                    //第二层封装
                    FilmInfo.FilmBean filmBean = new FilmInfo.FilmBean();
                    filmBean.setAid(aid);
                    filmBean.setAuthor(author);
                    filmBean.setCoins(coins);
                    filmBean.setCopyright(copyright);
                    filmBean.setCreate(create);

                    lists.add(filmBean);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }


        //显示Json数据
        tvJson.setText(json);
        tvJava.setText(filmInfo.toString());
    }
  • 实现图
    在这里插入图片描述
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值