1. 程式人生 > >JSON的四種類型的手動解析方式

JSON的四種類型的手動解析方式

一、什麼是JSON?

JSON是一種取代XML的資料結構,和xml相比,它更小巧但描述能力卻不差,由於它的小巧所以網路傳輸資料將減少更多流量從而加快速度。JSON就是一串字串 只不過元素會使用特定的符號標註。

{} 雙括號表示物件
[] 中括號表示陣列
“”雙引號內是屬性或值
:冒號表示後者是前者的值(這個值可以是字串、數字、也可以是另一個數組或物件)

所以 {“name”: “八戒”} 可以理解為是一個包含name為Michael的物件

而[{“name”: “猴哥”},{“name”: “八戒”}]就表示包含兩個物件的陣列

當然了,你也可以使用{“name”:[“Michael”,”Jerry”]}來簡化上面一部,這是一個擁有一個name陣列的物件

這裡寫圖片描述

解析分三個步驟:
1.獲取資料或者建立資料
2.解析資料
3.顯示到控制元件上去

第一種手動解析型別:將json格式的字串{}轉換為java物件(如下圖)

這裡寫圖片描述

jsonToJavaObjectByNative.java

 private void jsonToJavaObjectByNative() {
        //獲取或者建立json資料
        String json = "{\n" +
                "    \"id\":2,\n" +
                "    \"name\":\"猴哥\",\n"
+ " \"price\":12.3,\n" + " \"imgPath\":\"http://img00.hc360.com/cloth/201206/201206191116426249.jpg\"\n" + "\n" + "}"; users users = null; //解析json(getXXX或者optXXX都可以,最好使用optXXX,getXXX容易報空指標) try { JSONObject jsonObject = new
JSONObject(json); //String id1 = jsonObject.getString("id"); int id = jsonObject.optInt("id"); String name = jsonObject.getString("name"); double price = jsonObject.optDouble("price"); String imgPath = jsonObject.optString("imgPath"); //封裝實體類 users = new users(id, name, price, imgPath); } catch (JSONException e) { e.printStackTrace(); } //顯示json mtest01.setText("原始json資料:"+json);//原始 mtest02.setText("解析後:"+users.toString());//解析後 }

可以使用GsonFormat工具快速生成該類

package com.example.myzg2.json.bean;

/**
 * Created by Myzg2 on 2017/7/29.
 */

public class users {
    public users(int id, String name, double price, String imgPath) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.imgPath = imgPath;
    }

    public users() {
    }

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

    /**
     * id : 2
     * name : 猴哥
     * price : 12.3
     * imgPath : http://img00.hc360.com/cloth/201206/201206191116426249.jpg
     */

    private int id;
    private String name;
    private double price;
    private String imgPath;

    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 getImgPath() {
        return imgPath;
    }

    public void setImgPath(String imgPath) {
        this.imgPath = imgPath;
    }
}

這裡寫圖片描述

第二種手動解析型別:將json格式的字串[]轉換為java物件的集合

這裡寫圖片描述

jsonToJavaListByNative

 private void jsonToJavaListByNative() {
        //獲取資料或者建立資料
        String json = "\n" +
                "[{\n" +
                "    \"id\":1,\n" +
                "    \"name\":\"猴哥\",\n" +
                "    \"price\":12.3,\n" +
                "     \"imgPath\":\"http://img00.hc360.com/cloth/201206/201206191116426249.jpg\"\n" +
                "\n" +
                "},{\n" +
                "    \"id\":2,\n" +
                "    \"name\":\"八戒\",\n" +
                "    \"price\":63.2,\n" +
                "     \"imgPath\":\"http://img00.hc360.com/cloth/201206/201206191116426249.jpg\"\n" +
                "\n" +
                "}]";
        List<users> list = 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 i1 = jsonObject.optInt("");
                    String name = jsonObject.optString("name");
                    double price = jsonObject.optDouble("price");
                    String imagePath = jsonObject.optString("imagePath");
                    //封裝java物件
                    users users = new users(id, name, price, imagePath);
                    list.add(users);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        //顯示json資料
        mtest01.setText(json);//原始
        mtest02.setText(list.toString());//解析後
    }

第三種手動解析型別:複雜的json資料解析

這裡寫圖片描述

jsonToJavaByNative

  private void jsonToJavaByNative() {
        //獲取json資料
        String json = "{\n" +
                "    \"data\": {\n" +
                "        \"count\": 5,\n" +
                "        \"items\": [\n" +
                "            {\n" +
                "                \"id\": 45,\n" +
                "                \"title\": \"堅果\"\n" +
                "            },\n" +
                "            {\n" +
                "                \"id\": 145,\n" +
                "                \"title\": \"炒貨\"\n" +
                "            },\n" +
                "            {\n" +
                "                \"id\": 425,\n" +
                "                \"title\": \"蜜餞\"\n" +
                "            },\n" +
                "            {\n" +
                "                \"id\": 435,\n" +
                "                \"title\": \"果脯\"\n" +
                "            },\n" +
                "            {\n" +
                "                \"id\": 425,\n" +
                "                \"title\": \"禮盒\"\n" +
                "            }\n" +
                "        ]\n" +
                "    },\n" +
                "    \"rs_code\": \"1000\",\n" +
                "    \"rs_msg\": \"succss\"\n" +
                "}";
        //封裝java物件
        user_bead user_bead = new user_bead();

        try {
            JSONObject jsonObject = new JSONObject(json);

            //第一層解析
            String rs_code = jsonObject.optString("rs_code");
            String rs_msg = jsonObject.optString("rs_msg");
            JSONObject data = jsonObject.optJSONObject("data");
            //第一層封裝
            user_bead.setRs_code(rs_code);
            user_bead.setRs_msg(rs_msg);
            user_bead.DataBean datas=new user_bead.DataBean();
            user_bead.setData(datas);//集合

            //第二層解析
            int count = data.optInt("count");
            JSONArray jsonArray = data.optJSONArray("items");
            //第二層封裝
              datas.setCount(count);
            List<user_bead.DataBean.ItemsBean> jsonArrays=new ArrayList<>();
            datas.setItems(jsonArrays);//list集合
            //第三層解析
            //遍歷取得數組裡面所有json物件
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject1 = jsonArray.optJSONObject(i);
                if (jsonObject1 != null) {
                    int id = jsonObject1.optInt("id");
                    String title = jsonObject1.optString("title");

                    //第三層封裝
                  user_bead.DataBean.ItemsBean itemsBean = new user_bead.DataBean.ItemsBean();
                    itemsBean.setId(id);
                    itemsBean.setTitle(title);
                    jsonArrays.add(itemsBean);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        mtest01.setText(user_bead.toString());//原始
    }

user_bead

package com.example.myzg2.json.bean;

import java.util.List;

/**
 * Created by Myzg2 on 2017/7/30.
 */

public class user_bead {

    public user_bead(DataBean data, String rs_code, String rs_msg) {
        this.data = data;
        this.rs_code = rs_code;
        this.rs_msg = rs_msg;
    }

    public user_bead() {

    }

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

    /**
     * data : {"count":5,"items":[{"id":45,"title":"堅果"},{"id":145,"title":"炒貨"},{"id":425,"title":"蜜餞"},{"id":435,"title":"果脯"},{"id":425,"title":"禮盒"}]}
     * rs_code : 1000
     * rs_msg : succss
     */

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

    public static class DataBean {
        public DataBean(int count, List<ItemsBean> items) {
            this.count = count;
            this.items = items;
        }

        public DataBean() {
        }

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

        /**
         * count : 5
         * items : [{"id":45,"title":"堅果"},{"id":145,"title":"炒貨"},{"id":425,"title":"蜜餞"},{"id":435,"title":"果脯"},{"id":425,"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;
        }

        public static class ItemsBean {
            public ItemsBean(int id, String title) {
                this.id = id;
                this.title = title;
            }

            public ItemsBean() {
            }

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

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

第四種手動解析型別:特殊json資料解析

這裡寫圖片描述

jsonToJavaByNatives

 private void jsonToJavaByNatives()  {
        //獲取資料
        String json="{\n" +
                "\n" +
                "  \"code\":0,\n" +
                " \"list\":{\n" +
                "     \"0\":{\n" +
                "          \"aid\":\"6002545\",\n" +
                "          \"author\":\"頭條新聞\",\n" +
                "          \"coins\":175,\n" +
                "          \"copying\":\"Copy\",\n" +
                "          \"create\":\"2016-08-25 21:31\"\n" +
                "\n" +
                "         },\n" +
                " \"1\":{\n" +
                "          \"aid\":\"3602545\",\n" +
                "          \"author\":\"頭條新聞\",\n" +
                "          \"coins\":575,\n" +
                "          \"copying\":\"Copy\",\n" +
                "          \"create\":\"2016-08-25 21:35\"\n" +
                "\n" +
                "         }\n" +
                "\n" +
                "        }\n" +
                "}\n";
          //封裝java物件
        user_ts user_ts = new user_ts();
        //解析資料
        //第一層解析

        try {
            JSONObject jsonObject = new JSONObject(json);
            int code = jsonObject.optInt("code");
            JSONObject jsonObject1 = jsonObject.optJSONObject("list");
            //第一層封裝
            user_ts.setCode(code);
            List<user_ts.FilmBean> jsons=new ArrayList<>();
            user_ts.setList(jsons);//list集合

            // 第二層解析
            for (int i=0;i<jsonObject1.length();i++){
                JSONObject jsonObject2 = jsonObject1.optJSONObject(i + "");
                if (jsonObject2!=null){
                    String aid = jsonObject2.optString("aid");
                    String author = jsonObject2.optString("author");
                    int coins = jsonObject2.optInt("coins");
                    String copying = jsonObject2.optString("copying");
                    String create = jsonObject2.optString("create");

                    //第二層封裝
                     user_ts.FilmBean filmBean = new user_ts.FilmBean();
                    filmBean.setAid(aid);
                    filmBean.setAuthor(author);
                    filmBean.setCoins(coins);
                    filmBean.setCopying(copying);
                    filmBean.setCreate(create);
                    jsons.add(filmBean);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //顯示json資料
        mtest01.setText(user_ts.toString());//原始
    }

user_ts

package com.example.myzg2.json.bean;

import java.util.List;

/**
 * Created by Myzg2 on 2017/7/30.
 */

public class user_ts {
    private int code;
    private List<FilmBean> list;

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

      @Override
      public String toString() {
          return "FilmBean{" +
                  "aid='" + aid + '\'' +
                  ", author='" + author + '\'' +
                  ", coins=" + coins +
                  ", copying='" + copying + '\'' +
                  ", 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 getCopying() {
          return copying;
      }

      public void setCopying(String copying) {
          this.copying = copying;
      }

      public String getCreate() {
          return create;
      }

      public void setCreate(String create) {
          this.create = create;
      }
  }

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

本人只是一個學習階段的菜鳥,寫這個僅僅是為自己起到一個筆記作用。同時也方便大家。。。