[Android] Android serialization: Introduction to JSON parsing

 


1 Introduction

Schematic diagram


2. Grammar

  • JSON file containing a plurality of data, which in JSONthe form of value
// JSON实例
{"skill":{
          "web":[
                 {
                  "name":"html",
                  "year":"5"
                 },
                 {
                  "name":"ht",
                  "year":"4"
                 }],
           "database":[
                  {
                  "name":"h",
                  "year":"2"
                 }]
`}}
  • JSONThe content form of a value can be: "name-value" pair, array or object, which will be explained in detail below

Schematic diagram


3. Analysis method

  • AndroidParsing JSONa similar manner to data XMLparsing, mainly divided into two categories:
    Schematic diagram

  • Below, I will describe each method in detail

3.1 Android Studio comes with org.json parsing

  • Analysis principle: based on document-driven

Similar to XMLthe DOManalytical methods

  • Parsing process: read all files into the memory ->> traverse all data ->> retrieve the desired data as needed
  • Specific use
// 创建需解析的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 analysis

GoogleOpen source library

  • Analysis principle: based on event-driven
  • Analysis process: According to the required JSONdata, a JavaBeanclass corresponding to the data is established , and the required data can be parsed through simple operations
  • Specific use

Step 1: Create a JavaBean class corresponding to the JSON data (used to store the data that needs to be parsed)
Gson . The key to parsing = JSONWrite a corresponding based on the data JavaBean. The rules are:

Schematic diagram

The following two examples illustrate how to JSONcreate a JavaBeanclass through the document

/** 
  * 简单转换
  */ 
        // 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);
                }
            }
            }

If you think the conversion is too complicated, please use the tool directly: JSON string to Java entity class

Step 2: Import the GSON library
, Android Gradleimport dependencies

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

Step 3: Use Gson for analysis

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 analysis

  • Analysis principle: based on event-driven
  • Analysis process:
    1. Similarly GSON, first create JSONa J avaBeanclass corresponding to the data , and then analyze it through simple operations
    2. And Gsonparsing different: GSONon-demand resolution, i.e., to create the JavaBeanclass may not be covered completely parsed JSONdata, attributes created on demand; but Jacksonresolved corresponding JavaBeanto be the Jsondata of which all keyhave corresponding, i.e., it must be JSONdata in All parsed out, unable to parse on demand

But Jackson’s analysis speed and efficiency are higher than GSON

  • Specific use

Step 1: Establish Jsonthe javaBean corresponding to the data (the rules are the same as 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;
    }
}

Step 2: Analyze using Jackson method

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. Comparison of analysis methods

Schematic diagram



Guess you like

Origin blog.csdn.net/xfb1989/article/details/110130379