三、解析Json数据

2019-01-22  本文已影响0人  贵翼

一、Android原生技术解析Json数据

1.1 将json格式的字符串{}转换为Java对象

1.1.1 API

JSONObject(String json) : 将json字符串解析为json对象
Xxx getXxx(String name) : 根据name, 在json对象中得到对应的Value
Xxx optXxx(String name) : 根据name, 在json对象中得到对应的Value

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

1.1.2 测试数据

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

1.1.3 代码实现

 //解析数据
        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();
        }

1.2 将json格式的字符串[]转换为Java对象的List

1.2.1 API

JSONArray(String json) : 将json字符串解析为json数组
int length() : 得到json数组中元素的个数
Xxx getXxx(int index) : 根据下标得到json数组中对应的元素数据
Xxx optXxx(int index) : 根据下标得到json数组中对应的元素数据

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

1.2.2 测试数据

[
    {
        "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
    }
]

1.2.3 代码实现

 //解析Json数据
        ArrayList<ShopInfo> shopInfos = new ArrayList<>();
        try {
            JSONArray jsonArray = new JSONArray(json);
            
            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 shopInfo = new ShopInfo(id, name, price, imagePath);

                shopInfos.add(shopInfo);

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

1.3 复杂json数据解析

1.3.1 测试数据

{
    "data": {
        "count": 5,
        "items": [
            {
                "id": 45,
                "title": "坚果"
            },
            {
                "id": 132,
                "title": "炒货"
            },
            {
                "id": 166,
                "title": "蜜饯"
            },
            {
                "id": 195,
                "title": "果脯"
            },
            {
                "id": 196,
                "title": "礼盒"
            }
        ]
    },
    "rs_code": "1000",
    "rs_msg": "success"
}

1.3.2 使用HiJson工具格式化json数据

[HiJson](链接:https://pan.baidu.com/s/1QqKypwfvnn9eebSHLSXdQQ
提取码:hfm2 )

HiJson.png

1.3.3 使用GsonFormat插件在AndroidStudio中生成对应的bean

1.3.4 代码实现

先逐层解析,然后逐层封装

//解析数据,
        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");

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


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

            //第二层封装

            dataBean.setCount(count);

            List<DateInfo.DataBean.ItemsBean> itemBean = new ArrayList<>();
            dataBean.setItems(itemBean);

            //第三层解析
            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");

                    //第三层封装
                    DateInfo.DataBean.ItemsBean itemsBean = new DateInfo.DataBean.ItemsBean();
                    itemsBean.setId(id);
                    itemsBean.setTitle(title);
                    itemBean.add(itemsBean);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

1.4 特殊json数据解析

1.4.1 测试数据

特殊在键名是0和1,不能通过GsonFormat自动生成bean类,只能手动写

{
    "code": 0,
    "list": {
        "0": {
            "aid": "6008965",
            "author": "哔哩哔哩番剧",
            "coins": 170,
            "copyright": "Copy",
            "create": "2016-08-25 21:34"
        },
        "1": {
            "aid": "6008938",
            "author": "哔哩哔哩番剧",
            "coins": 404,
            "copyright": "Copy",
            "create": "2016-08-25 21:33"
        }
    }
}

1.4.2 手动写bean类

public  class FileBean {
    private int code;
    private List<FilmBean> filmBeans;

    @Override
    public String toString() {
        return "FileBean{" +
                "code=" + code +
                ", filmBeans=" + filmBeans +
                '}';
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public List<FilmBean> getFilmBeans() {
        return filmBeans;
    }

    public void setFilmBeans(List<FilmBean> filmBeans) {
        this.filmBeans = filmBeans;
    }

    public static class FilmBean {
        private String aid;
        private String author;
        private int coins;
        private String copyright;
        private String create;

        @Override
        public String toString() {
            return "FileBean{" +
                    "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;
        }
    }
}

1.4.3 手动解析Json数据

//解析数据
        try {
            //第一层解析
            JSONObject jsonObject = new JSONObject(json);
            int code = jsonObject.optInt("code");
            JSONObject list = jsonObject.optJSONObject("list");

            //第一层封装
            fileBean = new FileBean();
            fileBean.setCode(code);
            ArrayList<FileBean.FilmBean> fileBeans = new ArrayList<>();
            fileBean.setFilmBeans(fileBeans);

            //第二层解析
            for (int i = 0; i < list.length(); i++) {
                JSONObject jsonObject1 = list.optJSONObject(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");

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

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

二、Gson框架技术

下载Gson框架,下载地址
[Jar包](链接:https://pan.baidu.com/s/1hq00k7ZXm2Rypfof5_dhYA
提取码:yisw )
将Gson的jar包导入到项目中即可使用Gson

2.1 将json格式的字符串{}转换为Java对象

2.1.1 API

fromJson(String json, Class<T> classOfT);
第一个参数为json数据,第二个参数为对应的bean类。
注意:要求json对象中的key的名称与java对象对应的类中的属性名要相同。

2.1.2 测试数据

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

2.1.3 代码实现

//解析数据
        Gson gson = new Gson();
        ShopInfo shopInfo = gson.fromJson(json, ShopInfo.class);

2.2 将json格式的字符串[]转换为Java对象的List

2.2.1 API

List<ShopInfo> shops = gson.fromJson(json, new TypeToken<List<ShopInfo>>() {}.getType());

2.2.2 测试数据

[
    {
        "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
    }
]

2.2.3 代码实现

Gson gson = new Gson();
List<ShopInfo> shopInfos= gson.fromJson(json, 
new TypeToken<List<ShopInfo>>() { }.getType());

2.3 将Java对象转换为json字符串{}

2.3.1 API

String toJson(Object src);

2.3.2 代码示例

/**
 * 将Java对象转换为json字符串
*/
    private void JavaToJsonObjectByGson() {
        ShopInfo shopInfo = new ShopInfo(3, "螃蟹", 250.0, "pangxie");

        Gson gson = new Gson();
        String json = gson.toJson(shopInfo);

        tvOriginal.setText(shopInfo.toString());
        tvLast.setText(json);
    }

2.4 将Java对象的List转换为json字符串[]

2.4.1 API

String toJson(Object src);

2.4.2 代码示例

/**
 * Java对象的List转换为json
 */
    private void JavaListToJsonByGson() {
        ArrayList<ShopInfo> shops = new ArrayList<>();
        ShopInfo haidai = new ShopInfo(4, "海带", 13.3, "haidai");
        ShopInfo haima = new ShopInfo(5, "海马", 14.3, "haima");
        shops.add(haidai);
        shops.add(haima);
        String json = new Gson().toJson(shops);
        tvOriginal.setText(shops.toString());
        tvLast.setText(json);
    }

三、FastJson框架技术

下载FastJson,下载地址
[jar包](链接:https://pan.baidu.com/s/16g28Dd0TuOZWgDauRh7hWg
提取码:2pu1 )

3.1 将json格式的字符串{}转换为Java对象

3.1.1 API

注意:对应的bean类必须有默认的构造方法
parseObject(String json, Class<T> classOfT);

3.1.2 测试数据

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

3.1.3 代码示例

 /**
     * 将json转换为java对象
     */
    private void JsonToJavaObjectByFastJson() {
        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";

        ShopInfo shopInfo = JSON.parseObject(json, ShopInfo.class);

        tvOriginal.setText(json);
        tvLast.setText(shopInfo.toString());
    }

3.2 将json格式的字符串[]转换为Java对象的List

3.2.1 API

List<T> parseArray(String json,Class<T> classOfT);

3.2.2 测试数据

[
    {
        "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.2.3 代码示例

 List<ShopInfo> shopInfos = JSON.parseArray(json, ShopInfo.class);

3.3 将Java对象转换为Json字符串

3.3.1 API

String toJSONString(Object object);

3.3.2 代码示例

/**
     * java对象转换为json字符串
     */
    private void JavaObjectToJson() {
        ShopInfo shopInfo = new ShopInfo(7, "鱼", 1.3, "yu");

        String json = JSON.toJSONString(shopInfo);

        tvOriginal.setText(shopInfo.toString());
        tvLast.setText(json);
    }

3.4 将Java数组转换为Json字符串

3.4.1 API

String toJSONString(ArrayList<> lists);

3.4.2 代码演示

/**
     * java数组转换为json字符串
     */
    private void JavaListToJson() {
        ShopInfo pingguo = new ShopInfo(6, "苹果", 5.0, "pingguo");
        ShopInfo xeuli = new ShopInfo(7, "雪梨", 2.5, "xeuli");

        ArrayList<ShopInfo> shops = new ArrayList<>();

        shops.add(pingguo);
        shops.add(xeuli);

        String json = JSON.toJSONString(shops);

        tvOriginal.setText(shops.toString());
        tvLast.setText(json);
    }
上一篇下一篇

猜你喜欢

热点阅读