欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JSON的四种类型的手动解析方式

程序员文章站 2024-01-12 20:11:40
...

一、什么是JSON?

JSON是一种取代XML的数据结构,和xml相比,它更小巧但描述能力却不差,由于它的小巧所以网络传输数据将减少更多流量从而加快速度。JSON就是一串字符串 只不过元素会使用特定的符号标注。

{} 双括号表示对象
[] 中括号表示数组
“”双引号内是属性或值
:冒号表示后者是前者的值(这个值可以是字符串、数字、也可以是另一个数组或对象)

所以 {“name”: “八戒”} 可以理解为是一个包含name为Michael的对象

而[{“name”: “猴哥”},{“name”: “八戒”}]就表示包含两个对象的数组

当然了,你也可以使用{“name”:[“Michael”,”Jerry”]}来简化上面一部,这是一个拥有一个name数组的对象

JSON的四种类型的手动解析方式

解析分三个步骤:
1.获取数据或者创建数据
2.解析数据
3.显示到控件上去

第一种手动解析类型:将json格式的字符串{}转换为java对象(如下图)

JSON的四种类型的手动解析方式

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的四种类型的手动解析方式

第二种手动解析类型:将json格式的字符串[]转换为java对象的集合

JSON的四种类型的手动解析方式

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数据解析

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数据解析

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

本人只是一个学习阶段的菜鸟,写这个仅仅是为自己起到一个笔记作用。同时也方便大家。。。

相关标签: json 解析json