SoFunction
Updated on 2025-04-09

Use and compare 4 ways of parsing JSON in Android

1 Analysis of Android SDK

Analysis principle: Based on document driver, you need to read all files into memory, then traverse all data, and retrieve the desired data as needed.

Related categories:

  • JSONObject
  • JSONArray
  • JSONTokener
public Object nextValue() throws JSONException {
    int c = nextCleanInternal();
    switch (c) {
        case -1:
            throw syntaxError("End of input");
            
        case '{':
            return readObject();
            
        case '[':
            return readArray();
            
        case ''':
        case '"':
            return nextString((char) c);
            
        default:
            pos--;
            return readLiteral();
    }
}
  • JSONStringer
  • JSONException

The following is the sample code that comes with Json parsing method of Android SDK:

/**
 * @Description: The Json analysis method that comes with SDK
 * @CreateDate: 2022/3/22 10:30 am
 */
public class OrgJsonUtil {
    /**
 * Generate Json
 */
    public static void createJson(Context context) {
        try {
            File file = new File((), "");
            //Instantiate a JSONObject            JSONObject student = new JSONObject();
            //Add data to the object            ("name", "Musk");
            ("sex", "male");
            ("age", 50);

            JSONObject course1 = new JSONObject();
            ("name", "math");
            ("score", 98.2f);
            JSONObject course2 = new JSONObject();
            ("name", "Chinese");
            ("score", 99);

            //Instantiate a JSONArray            JSONArray courses = new JSONArray();
            (0, course1);
            (1, course2);
            ("courses", courses);

            //Write data            FileOutputStream fos = new FileOutputStream(file);
            (().getBytes());
            ();
            ("TAG", "createJson: " + student);

            (context, "Json created successfully", Toast.LENGTH_SHORT).show();

        } catch (Exception e) {
            ();
        }
    }

    /**
 * Analyze Json
 */
    public static void parseJson(Context context) {
        try {
            //Read the data            File file = new File((), "");
            FileInputStream fis = new FileInputStream(file);
            InputStreamReader isr = new InputStreamReader(fis);
            BufferedReader br = new BufferedReader(isr);
            String line;
            StringBuffer sb = new StringBuffer();
            while (null != (line = ())) {
                (line);
            }
            ();
            ();
            ();

            Student student = new Student();
            JSONObject studentJsonObject = new JSONObject(());

            //Get object            //Use optString to return an empty string "" when the corresponding value is not obtained, while using getString will be exception            String name = ("name", "");
            String sex = ("sex", "female");
            int age = ("age", 18);
            (name);
            (sex);
            (age);

            //Get the array            List<Course> courses = new ArrayList<>();
            JSONArray coursesJsonArray = ("courses");
            if (coursesJsonArray != null && () > 0) {
                for (int i = 0; i < (); i++) {
                    JSONObject courseJsonObject = (i);
                    Course course = new Course();
                    String courseName = ("name", "discipline");
                    float score = (float) ("score", 0);
                    (courseName);
                    (score);
                    (course);
                }
            }
            (courses);

            ("TAG", "parseJson: " + student);
            (context, "Json parsing successfully", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            ();
        }
    }

}

2 Gson analysis

Analytical principle: based on event-driven.

Advantages:

  • Fast and efficient
  • Small amount of code
  • Object-oriented
  • Easy to transfer and parse
  • Can be parsed on demand

Analysis process: Create a JavaBean class corresponding to JSON data based on the data you need, and you can parse the required data through simple operations.
Gson does not require that all the properties in the JavaBean class must be the same as all keys in the JSON data, and data can be retrieved as needed.

use:

  • JSON braces correspond to an object

    • There is a key, value in the object
    • JavaBean class attribute name = key
  • JSON's brackets correspond to an array

  • The corresponding array in JavaBean is also

  • There can be values/objects in the object

  • If there are only values ​​and no keys in the object, it means it is a pure array, corresponding to the array type in JavaBean

  • If there are values ​​and keys in the object, it means it is an object array, corresponding to the internal class in JavaBean

  • Object nesting

    • Create an inner class The name of the inner class object = the key of the parent object, similar to an object array
{
    "key":"value",
    "simpleArray":[
        1,
        2,
        3
    ],
    "arrays":[
        {
            "arrInnerClsKey":"arrInnerClsValue",
            "arrInnerClsKeyNub":1
        }
    ],
    "innerclass":{
        "name":"Musk",
        "age":50,
        "sex":"male"
    }
}

Corresponding JavaBean:

public class JsonJavaBean {
    private String key;
    private List<Integer> simpleArray;
    private List<ArraysBean> arrays;
    private InnerclassBean innerclass;

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
         = key;
    }

    public List<Integer> getSimpleArray() {
        return simpleArray;
    }

    public void setSimpleArray(List<Integer> simpleArray) {
         = simpleArray;
    }

    public List<ArraysBean> getArrays() {
        return arrays;
    }

    public void setArrays(List<ArraysBean> arrays) {
         = arrays;
    }

    public InnerclassBean getInnerclass() {
        return innerclass;
    }

    public void setInnerclass(InnerclassBean innerclass) {
         = innerclass;
    }

    private static class ArraysBean {
        private String arrInnerClsKey;
        private int arrInnerClsKeyNub;

        public String getArrInnerClsKey() {
            return arrInnerClsKey;
        }

        public void setArrInnerClsKey(String arrInnerClsKey) {
             = arrInnerClsKey;
        }

        public int getArrInnerClsKeyNub() {
            return arrInnerClsKeyNub;
        }

        public void setArrInnerClsKeyNub(int arrInnerClsKeyNub) {
             = arrInnerClsKeyNub;
        }
    }

    private static class InnerclassBean {
        private String name;
        private int age;
        private String sex;

        public String getName() {
            return name;
        }

        public void setName(String name) {
             = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
             = age;
        }

        public String getSex() {
            return sex;
        }

        public void setSex(String sex) {
             = sex;
        }
    }
}

Gson parsing sample code:

/**
 * @Description: Gson usage example
 * @CreateDate: 2022/3/22 12:51 pm
 */
public class GsonUse {

    public static void main(String[] args) throws Exception {
        Student student = new Student();
        ("John");
        (20);
        ("male");
        List&lt;Course&gt; courses = new ArrayList&lt;&gt;();
        (new Course("Chinese", 99));
        (new Course("geography", 59));
        (courses);

        Gson gson = new Gson();

        //Create files in the json folder in the root directory of the project        File file = new File("json/");
        FileOutputStream fos = new FileOutputStream(file);
        OutputStreamWriter osw = new OutputStreamWriter(fos, "utf-8");
        JsonWriter jw = new JsonWriter(osw);
        (student, new TypeToken&lt;Student&gt;() {
        }.getType(), jw);
        ();
        ();

        //Deserialize to JavaBean        FileInputStream fis = new FileInputStream(file);
        InputStreamReader isr = new InputStreamReader(fis);
        JsonReader jr = new JsonReader(isr);
        Student student1 = (jr, new TypeToken&lt;Student&gt;() {
        }.getType());
        (student1);
    }
}

3 Jackson analysis

Analytical principle: based on event-driven.

Advantages: The most analytical efficiency; the advantages are particularly obvious in the case of large amount of data and the stock is small.

Disadvantages: All keys in Json data correspond to each other, that is, the document must be completely parsed. If you want to parse it as needed, you can split Json to read it. The operation and parsing methods are complex.

Applicable scenarios: Suitable for situations where super-large JSON documents need to be processed, no need to parse JSON documents on demand, and high performance requirements.

Analysis process:

  • Similar to Gson, first create a JavaBean class corresponding to JSON data, and then parse it through simple operations.
  • Unlike Gson parsing, Gson can parse on demand, that is, the JavaBean class created does not necessarily fully cover the JSON data to be parsed, and attributes are created as needed; but the corresponding JavaBeans for Jackson parsing must correspond to all keys in the Json data, that is, all the data in JSON must be parsed out, and cannot be parsed on demand.

use:

Introduce dependencies

//Jackson
implementation ':jackson-databind:2.13.1'
implementation ':jackson-core:2.13.1'
implementation ':jackson-annotations:2.13.1'

/**
 * @Description: Jackson usage example
 * @CreateDate: 2022/3/22 1:47 pm
 */
public class JacksonUse {
    public static void main(String[] args) throws Exception {
        Student student = new Student();
        ("Lili");
        ("female");
        (26);
        List&lt;Course&gt; courses = new ArrayList&lt;&gt;();
        (new Course("Art", 100));
        (new Course("Love", 99));
        (courses);

        ObjectMapper objectMapper = new ObjectMapper();
        //Serialize to generate json file        File file = new File("json/");
        FileOutputStream fos = new FileOutputStream(file);
        (fos, student);

        //Deserialize the json file to JavaBean        Student student1 = (file, );
        (student1);
    }
}

Note: The key in json must correspond to all fields in JavaBean.

If there is no correspondence, for example, if there is an additional "hobby" field in json and not in JavaBean, an error will be reported when running:

Exception in thread "main" : Unrecognized field "hobby" (class ), not marked as ignorable (4 known properties: "courses", "name", "sex", "age"])
 at [Source: (File); line: 3, column: 13] (through reference chain: ["hobby"])

4 Fastjson analysis

Features:

  • Fast FAST (faster than any one)
  • Object-oriented
  • Powerful (supports any java bean Class, Collection, Map, Date or enum in ordinary JDK classes)
  • Zero dependency (just need JDK)
  • Support annotation, full type serialization

use:

Introduce dependencies

implementation ':fastjson:1.2.76'
/**
 * @Description: Fastjson usage example
 * @CreateDate: 2022/3/22 2:10 pm
 */
public class FastjsonUse {
    public static void main(String[] args) throws Exception {
        Student student = new Student();
        ("Lili");
        ("female");
        (26);
        List&lt;Course&gt; courses = new ArrayList&lt;&gt;();
        (new Course("Art", 100));
        (new Course("Love", 99));
        (courses);

        //Serialize to generate json        File file = new File("json/");
        FileOutputStream fos = new FileOutputStream(file);
        (fos, student);

        //Deserialization json to JavaBean        FileInputStream fis = new FileInputStream(file);
        Student student1 = (fis, );
        (student1);
    }
}

The above is a comparison of several JSON parsing methods. At present, Gson and FastJson are relatively used. For more related Android JSON content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!