解析成java对象

统一布局如下

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".json.activity.NativeJsonParseActivity">

    <include layout="@layout/titlebar"></include>

    <Button
        android:id="@+id/btn_native_tojavaobject"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:text="将json对象转换为java对象" />

    <Button
        android:id="@+id/btn_native_tojavalist"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:text="将json数组转换为java集合" />

    <Button
        android:id="@+id/btn_native_complex"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:text="复杂Json数据解析" />

    <Button
        android:id="@+id/btn_native_special"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:text="特殊Json数据解析" />


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:text="原始数据"
        android:textColor="@android:color/holo_blue_light"
        android:textSize="18sp" />
    <TextView
        android:id="@+id/tv_native_orignal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:textSize="18sp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:text="转换后的数据"
        android:textColor="@android:color/holo_blue_light"
        android:textSize="18sp" />

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

        android:textSize="18sp" />
</LinearLayout>

理解Json解析的几个示例

json-1

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

json-2

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

创建JavaBean(json-1/-2)

public class ShopInfo {
    private int id;
    private String name;
    private  double price;
    private  String imagePath;

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

    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 + '\'' +
                '}';
    }
}

解析方法(将json格式的对象转换为java对象)

 //将json格式的对象转换为java对象
    private void jsonToJavaObjectByNative() {
        //获取或创建JSON数据
        String json = "{  \"id\":2, \"name\":\"大虾\", " +
                "  \"price\":12.3,  " +
                " \"imagePath\":\"http://192.168.10.165:8080/L05_Server/images/f1.jpg\" }";
        //解析json getXXX and  optXXX(会有默认值)
        ShopInfo shopInfo = null;
        try {
            JSONObject jsonObject = new JSONObject(json);
//            int id = jsonObject.getInt("id");
            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();
        }
        //显示json
        tv_native_orignal.setText(json);
        tv_native_last.setText(shopInfo.toString());
    }

解析方法(将json格式的对象转换为java对象的list)

//将json格式的对象转换为java对象的list
    private void jsonToJavaListByNative() {
        //获取或创建JSON数据
        String json = "[ \n" +
                "{  \"id\":1, \"name\":\"大虾1\",   \"price\":12.3,  " +
                " \"imagePath\":\"http://192.168.10.165:8080/f1.jpg\" }," +
                " {  \"id\":2, \"name\":\"大虾2\",   \"price\":12.5, " +
                "  \"imagePath\":\"http://192.168.10.165:8080/f2.jpg\" } ] ";
        //解析json
        List<ShopInfo> shops = new ArrayList<>();
        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.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);
                    shops.add(shopInfo);
                }

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //显示json
        tv_native_orignal.setText(json);
        tv_native_last.setText(shops.toString());
    }

理解Json解析的几个示例

复杂json解析

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

javaBean对象

public class DataInfo {

    /**
     * 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
     */

    private DataBean data;
    private String rs_code;
    private String 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;
    }
    @Override
    public String toString() {
        return "DataInfo{" +
                "data=" + data +
                ", rs_code='" + rs_code + '\'' +
                ", rs_msg='" + rs_msg + '\'' +
                '}';
    }
    public static class DataBean {


        /**
         * count : 5
         * items : [{"id":45,"title":"坚果"},{"id":132,"title":"炒货"},{"id":166,"title":"蜜饯"},{"id":195,"title":"果脯"},{"id":196,"title":"礼盒"}]
         */

        private int count;
        private List<ItemsBean> 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;
        }
        @Override
        public String toString() {
            return "DataBean{" +
                    "count=" + count +
                    ", items=" + items +
                    '}';
        }
        public static class ItemsBean {

            /**
             * id : 45
             * title : 坚果
             */

            private int id;
            private String 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;
            }
            @Override
            public String toString() {
                return "ItemsBean{" +
                        "id=" + id +
                        ", title='" + title + '\'' +
                        '}';
            }

        }
    }
}


解析方法

 //复杂json数据的解析
    private void jsonToJavaOfComplex() {
        //获取或创建JSON数据
        String json = "{ \"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\" } ";
       //封装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.optJSONArray("items");
            List<DataInfo.DataBean.ItemsBean> itemsBeans = new ArrayList<>();
            dataBean.setItems(itemsBeans);
            //第三层解析
            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);
                    itemsBeans.add(bean);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        //显示json
        tv_native_orignal.setText(json);
        tv_native_last.setText(dataInfo.toString());
    }

理解Json解析的几个示例

特殊json解析

  • 特殊在于list节点下是1或者0的数字 使用GsonFormat会出现问题

创建javaBean

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

public class FilmInfo {
    private int code;
    private List<FilmBean> 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;
    }

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

    public static class FilmBean{
        private String aid;
        private String author;
        private int  coins;
        private String copyright;
        private String 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;
        }

        @Override
        public String toString() {
            return "FilmBean{" +
                    "aid='" + aid + '\'' +
                    ", author='" + author + '\'' +
                    ", coins=" + coins +
                    ", copyright='" + copyright + '\'' +
                    ", create='" + create + '\'' +
                    '}';
        }
    }

}

解析方法(特殊json数据的解析)

//特殊json数据的解析
    private void jsonToJavaOfSpecial() {
    //获取或创建JSON数据
        String json = "{\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" +
                "}\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);
            ArrayList<FilmInfo.FilmBean> filmBeans = new ArrayList<>();
            filmInfo.setList(filmBeans);
            //第二层解析
            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 bean = new FilmInfo.FilmBean();
                    bean.setAid(aid);
                    bean.setAuthor(author);
                    bean.setCoins(coins);
                    bean.setCopyright(copyright);
                    bean.setCreate(create);
                    filmBeans.add(bean);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //显示json
        tv_native_orignal.setText(json);
        tv_native_last.setText(filmInfo.toString());
    }

理解Json解析的几个示例

相关文章: