2023-06-07  阅读(161)
原文作者:Carson 原文地址:https://blog.csdn.net/carson_ho/category_9272167.html

前言

  • 现今最主流的数据交换格式 非 JSON莫属
  • 今天,我将全面介绍 JSON & 解析方式(GsonAS自带org.jsonJackson),希望你们会喜欢

目录

202306072044376112.png


1. 简介

202306072044382213.png


2. 语法

  • 1个JSON文件里含多个数据,这些数据 以 JSON值 的形式 存在
    // JSON实例
    {"skill":{
              "web":[
                     {
                      "name":"html",
                      "year":"5"
                     },
                     {
                      "name":"ht",
                      "year":"4"
                     }],
               "database":[
                      {
                      "name":"h",
                      "year":"2"
                     }]
    `}}
  • 1个JSON值的内容形式可以是:”名称 - 值“对、数组 或 对象,下面将详细说明

202306072044389504.png


3. 解析方式

  • Android 解析 JSON数据的方式 类似 XML解析,主要分为2大类:

    202306072044395995.png

  • 下面,我将详细介绍每种方式

3.1 Android Studio自带org.json解析

  • 解析原理:基于文档驱动

类似于XMLDOM解析方式

  • 解析流程:把全部文件读入到内存中 ->> 遍历所有数据 ->> 根据需要检索想要的数据
  • 具体使用
    // 创建需解析的JSON数据:student.json
    // 将该文件放入到本地assets文件夹里
    {
    "student":[
    	   		{"id":1,"name":"小明","sex":"男","age":18,"height":175},
      			{"id":2,"name":"小红","sex":"女","age":19,"height":165},
    	   		{"id":3,"name":"小强","sex":"男","age":20,"height":185}
    	  	  ],
    "cat":"it"
    }
    
    // 具体解析
    import android.os.Bundle;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    
    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            EntityStudent student = new EntityStudent();
    
    
            try {
                //从assets获取json文件
                InputStreamReader isr = new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("assets/" + "student.json"));
                //字节流转字符流
               BufferedReader bfr = new BufferedReader(isr);
                String line ;
                StringBuilder stringBuilder = new StringBuilder();
                while ((line = bfr.readLine())!=null){
                    stringBuilder.append(line);
                }//将JSON数据转化为字符串
                JSONObject root = new JSONObject(stringBuilder.toString());
                //根据键名获取键值信息
                System.out.println("root:"+root.getString("cat"));
                JSONArray array = root.getJSONArray("student");
                for (int i = 0;i < array.length();i++)
                {
                    JSONObject stud = array.getJSONObject(i);
                    System.out.println("------------------");
                    System.out.print("id="+stud.getInt("id")+ ","));
                    System.out.print("name="+stud.getString("name")+ ","));
                    System.out.print("sex="+stud.getString("sex")+ ","));
                    System.out.print("age="+stud.getInt("age")+ ","));
                    System.out.println("height="+stud.getInt("height")+ ","));
    				bfr.close();
               	 	isr.close();
    				is.close();//依次关闭流
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
    
        }
    }

3.2 Gson解析

Google的开源库

  • 解析原理:基于事件驱动
  • 解析流程:根据所需取的数据 建立1个对应于JSON数据的JavaBean类,即可通过简单操作解析出所需数据
  • 具体使用

步骤1:创建一个与JSON数据对应的JavaBean类(用作存储需要解析的数据)
Gson解析的关键 = 根据JSON数据 写出一个对应的JavaBean,规则是:

202306072044402476.png

下面用2个例子说明 如何通过JSON文档创建JavaBean

    /** 
      * 简单转换
      */ 
            // JSON数据1
            String json = "{\"id\":1,\"name\":\"小明\",\"sex\":\"男\",\"age\":18,\"height\":175}";
    
            // 对应的JavaBean类
            public class EntityStudent {
            private int id;
            private String name;
            private String sex;
            private int age;
            private int height;
    
            public void setId(int id){
                this.id = id;
            }
            public void setName(String name){
                this.name = name;
            }
            public void setSex(String sex){
                this.sex = sex;
            }
            public void setAge(int age){
                this.age = age;
            }
            public void setHeight(int height){
                this.height = height;
            }
            public int getId(){
                return id;
            }
            public String getName(){
                return name;
            }
            public String getSex(){
                return sex;
            }
            public int getAge(){
                return age;
            }
            public int getHeight(){
                return  height;
            }
            public void show(){
                        System.out.print("id=" + id + ",");
                        System.out.print("name=" + name+",");
                        System.out.print("sex=" + sex+",");
                        System.out.print("age=" + age+",");
                        System.out.println("height=" + height + ",");
    
            }
            }
    
    /** 
      * 复杂转换
      */ 
            // JSON数据2(具备嵌套)
            {"translation":["车"],
              "basic":
                {
                  "phonetic":"kɑː",
                  "explains":["n. 汽车;车厢","n. (Car)人名;(土)贾尔;(法、西)卡尔;(塞)察尔"]},
              "query":"car",
              "errorCode":0,
              "web":[{"value":["汽车","车子","小汽车"],"key":"Car"},
                     {"value":["概念车","概念车","概念汽车"],"key":"concept car"},
                     {"value":["碰碰车","碰撞用汽车","碰碰汽车"],"key":"bumper car"}]
            }
    
            // 对应的复杂的JSON数据对应的JavaBean类
            public class student {
                public String[] translation;    //["车"]数组
                public basic basic;             //basic对象里面嵌套着对象,创建一个basic内部类对象
                public  static class basic{     //建立内部类
                    public String phonetic;
                    public String[] explains;
                }
                public String query;
                public int errorCode;
                public List<wb> web;            //web是一个对象数组,创建一个web内部类对象
                public static class wb{         
                        public String[] value;
                        public String key;
                    }
    
                public void show(){
                    //输出数组
                    for (int i = 0;i<translation.length;i++)
                    {
                    System.out.println(translation[i]);
                    }
                    //输出内部类对象
                    System.out.println(basic.phonetic);
                    //输出内部类数组
                    for (int i = 0;i<basic.explains.length;i++){
                        System.out.println(basic.explains[i]);
                    }
                    System.out.println(query);
                    System.out.println(errorCode);
                    for (int i = 0;i<web.size();i++){
                        for(int j = 0; j<web.get(i).value.length;j++)
                        {
                            System.out.println(web.get(i).value[j]);
                        }
                        System.out.println(web.get(i).key);
                    }
                }
                }

若觉得转换过于复杂,请直接使用工具:JSON字符串 转 Java实体类

步骤2:导入GSON库
Android Gradle导入依赖

    dependencies {
      compile 'com.google.code.gson:gson:2.3.1'
    }

步骤3:使用Gson进行解析

    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            // 1. 创建Gson对象
            Gson gson = new Gson();
    
            // 2. 创建JavaBean类的对象
            Student student = new EntityStudent();
    
            // 3. 使用Gson解析:将JSON数据转为单个类实体
            String json = "{\"id\":1,\"name\":\"小明\",\"sex\":\"男\",\"age\":18,\"height\":175}";
            student = gson.fromJson(json,Student.class);
            // 解析:JavaBean对象 = gson.fromJson(son,javaBean类类名.class);
    
            // 4. 调用student方法展示解析的数据
            student.show();
            
            // 5. 将Java集合转换为json
            String json2 = gson.toJson(List);        
            System.out.println(json2);
        }
    }

3.3 Jackson解析

  • 解析原理:基于事件驱动

  • 解析过程:

    1. 类似 GSON,先创建1个对应于JSON数据的JavaBean类,再通过简单操作即可解析
    2. Gson解析不同的是:GSON可按需解析,即创建的JavaBean类不一定完全涵盖所要解析的JSON数据,按需创建属性;但Jackson解析对应的JavaBean必须把Json数据里面的所有key都有所对应,即必须把JSON内的数据所有解析出来,无法按需解析

但Jackson的解析速度、效率都 高于 GSON

  • 具体使用

步骤1:建立Json数据对应的javaBean(规则同GSON)

    // 创建需解析的JSON数据:student.json
    // 将该文件放入到本地assets文件夹里
    {"student":
              [
               {"id":1,"name":"小明","sex":"男","age":18,"height":175,"date":[2013,8,11]},
               {"id":2,"name":"小红","sex":"女","age":19,"height":165,"date":[2013,8,23]},
               {"id":3,"name":"小强","sex":"男","age":20,"height":185,"date":[2013,9,1]}
              ],
      "grade":"2"
    }
    
    // JavaBean类
    class test {
        private  List<stu> student = new ArrayList<stu>();
    
        private  int grade;
    
        public void setStudent(List<stu> student){
            this.student = student;
        }
        public List<stu> getStudent(){
            return student;
        }
        public void setGrade(int grade){
            this.grade = grade;
        }
        public int getGrade(){
            return grade;
        }
        private static class stu {
            private  int id;
            private  String name;
            private  String sex;
            private  int age;
            private  int height;
            private  int[] date;
    
            public void setId(int id){
                this.id = id;
            }
            public int getId(){
                return id;
            }
            public void setName(String name){
                this.name = name;
            }
            public String getName(){
                return  name;
            }
            public void setSex(String sex){
                this.sex = sex;
            }
            public String getSex(){
                return sex;
            }
            public void  setAge(int age){
                this.age = age;
            }
            public int getAge(){
                return age;
            }
            public void setHeight(int height){
                this.height = height;
            }
            public int getHeight(){
                return height;
            }
            public void setDate(int[] date){
                this.date = date;
            }
            public int[] getDate(){
                return date;
            }
        }
    
        public String tostring(){
            String str = "";
            for (int i = 0;i<student.size();i++){
                str += student.get(i).getId() + " " + student.get(i).getName() + " " + student.get(i).getSex() + " " + student.get(i).getAge() + " " + student.get(i).getHeight() ;
                for (int j = 0;j<student.get(i).getDate().length;j++) {
                    str += student.get(i).getDate()[j]+ " " ;
                }
                str += "\n";
            }
            str += "\n"+getGrade();
            return str;
        }
    }

步骤2:利用Jackson方法进行解析

    public class MainActivity extends AppCompatActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                // 1. //从assets获取json文件
                InputStreamReader isr = new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("assets/" + "student.json"),"utf-8");
                BufferedReader bfr = new BufferedReader(isr);
                String line;
                StringBuilder stringBuilder = new StringBuilder();
                while ((line = bfr.readLine())!=null){
                    stringBuilder.append(line);
                }
                // 2. 将JSON数据转化为字符串
                System.out.println(stringBuilder.toString());
                System.out.println(tes.tostring());
    
            } catch (IOException e) {
                e.printStackTrace();
            }
    
        }
    
    }

4. 解析方式对比

202306072044407877.png


5. 与XML解析对比

  • 对于 同样作为主流的数据交换格式XML来说,二者对比如下:

    202306072044413278.png

  • 总的来说,相比于 XMLJSON大小更小、解析方法更简单、解析速度更快。所以,JSON一定是你在数据交换格式选型中的首选

阅读全文
  • 点赞