Android-JSON parsing (Gson, org.json, Jackson, FastJson)

I would like to record the learning process with articles, and please indicate if there are any mistakes.

Introduction to JSON

  • Definition:
    a lightweight text data interchange format
  • Role:
    data tagging, storage & transmission

  • Shorthand usage:
    {} means object; [] means array; "" means property or value; :colon means the latter is the value of the former, which can be an object, an array, a string, a number, etc.

  • Features:

    • lightweight
    • Good readability & fast writing
    • platform independent

Analysis method

Similar XMLanalysis, divided into two categories:

Analysis method Implementation principle Specific forms
Document driven Before parsing the JSON document, store the entire JSON document in memory Built-in org.json parsing
event driven Perform different parsing operations according to different demand events Gson 、 Jackson 、 FastJson

Below we introduce the use of the four analysis methods based on examples.

It is recommended to continue reading the Demo address with the Demo: DemoXML-Json

Data to be parsed JSON(located assets\below complex.json)

{
  "name":"王尼玛",
  "fans":
  [
    {
      "name":"小王",
      "age":"7"
    },
    {
      "name":"小尼玛",
      "age":"10"
    }
  ]
}

org.json parsing

  • Parsing process: read all files into memory ->> traverse all data ->> retrieve data on demand
  • Example analysis:
private void parse_json(){
        try {

            StringBuilder textShow = new StringBuilder("This is parsed by org.json" + "\n");
            //获取根节点对象
            JSONObject rootObject = new JSONObject(get_json("complex.json"));
            //获取根节点对象的属性name
            textShow.append("star name is : "+ rootObject.get("name") + "\n");
            //获取根节点对象的内部数组Fans[]
            JSONArray jsonArray =  rootObject.getJSONArray("fans");
            //遍历数组Fans[[]
            for (int i = 0; i < jsonArray.length(); i++){
                //获取数组Fans中的每一个对象fans
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                //获取fans的属性
                textShow.append("fans name is + " + jsonObject.getString("name") + "\n");
                textShow.append("fans age is + " + jsonObject.getString("age") + "\n");
            }
            jsonText.setText(textShow);

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

Gson parsing

  • Parsing process: Create a class corresponding to the JSONdata according to the data to be fetched, JavaBeanand then the required data can be parsed through simple operations
  • Example analysis:

1. Create a JavaBean class corresponding to JSON data (for storing data)

It is strongly recommended to create JavaBean classes via the GsonFormat plugin


package com.example.niyati.demoxmljson.Entity;
import java.util.List;

public class RootBean {

    private String name;
    private List<Fans> fans;
    public void setName(String name) {
         this.name = name;
     }
     public String getName() {
         return name;
     }

    public void setFans(List<Fans> fans) {
         this.fans = fans;
     }
     public List<Fans> getFans() {
         return fans;
     }

}
package com.example.niyati.demoxmljson.Entity;

public class Fans {

    private String name;
    private String age;
    public void setName(String name) {
         this.name = name;
     }
     public String getName() {
         return name;
     }

    public void setAge(String age) {
         this.age = age;
     }
     public String getAge() {
         return age;
     }

}

2. Import Gson library

importing Android Gradledependencies

implementation 'com.google.code.gson:gson:2.8.0'

3. Parse using Gson

private void parse_gson(){
        try {
            StringBuilder textShow = new StringBuilder("This is parsed by GSON" + "\n");
            //获取Gson对象
            Gson gson = new Gson();
            //将JSON数据转换为JavaBean类实体
            RootBean json = gson.fromJson(get_json("complex.json"),RootBean.class);
            //获取RootBean对象的熟悉
            textShow.append("star name is :"+json.getName()+"\n");
            //获取RootBean对象中的Fans[]数组
            for (Fans fans:json.getFans()) {
                textShow.append("fans name is :" + fans.getName() + "\n");
                textShow.append("fans age is :" + fans.getAge() + "\n");
            }
            jsonText.setText(textShow);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

Jackson Analysis

  • Parsing process:

    1. Similarly GSON, first create JSONa class corresponding to the data JavaBean, and then parse it through a simple operation
    2. GsonThe difference from parsing is that it GSONcan be parsed on demand, that is, the created JavaBeanclass may not completely cover the JSONdata to be parsed, and attributes are created as needed; but Jacksonthe corresponding parsing JavaBeanmust correspond to Jsonall the data in the data key, that is JSON, the data in the All parsed out, unable to parse on demand
  • Example analysis:
    1. Create a JavaBean class corresponding to JSON data, same as Gson

    2. Import the Jackson package
    and put it in the jackson-all-1.9.0.jarproject libspath, Android studioright-click in the middle and select itadd as a library

    3. Use Jackson for parsing

private void parse_jackson(){
        try {
            StringBuilder textShow = new StringBuilder("this is parsed by jackson" + "\n");
            //获取ObjectMapper对象
            ObjectMapper mapper = new ObjectMapper();
            //Json数据转化为类实体,以下同Gson用法相似
            RootBean root = mapper.readValue(get_json("complex.json"),RootBean.class);
            textShow.append(root.getName()+ "\n");
            for (Fans fans: root.getFans()){
                textShow.append(fans.getName()+ "\n");
                textShow.append(fans.getAge()+ "\n");
            }
            jsonText.setText(textShow);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

FastJson analysis

  • Parsing process: Create a class corresponding to the JSONdata according to the data to be fetched, JavaBeanand then the required data can be parsed through simple operations
  • Example analysis:
    1. Create a JavaBean class corresponding to JSON data, same as Gson

    2. Add FastJson dependency
    implementation 'com.alibaba:fastjson:1.2.31'

    3. Parsing with FastJson

private void parse_fastjson(){
        try {
            StringBuilder textShow = new StringBuilder("This is parsed by fastjson"+"\n");
            //转化Json数据到类实体
            RootBean root = JSON.parseObject(get_json("complex.json"),RootBean.class);
            //以下类似Gson
            textShow.append(root.getName()+ "\n");
            for (Fans fans:root.getFans()){
                textShow.append(fans.getName()+ "\n");
                textShow.append(fans.getAge()+ "\n");
            }
            jsonText.setText(textShow);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Analysis method summary

org.json:

  • Advantages: high access efficiency during frequent operations (documents are stored in memory)
  • Disadvantage: consumes memory
  • Application scenario: XML documents are small and need to be parsed & accessed frequently

Gson:

  • Advantages: simple parsing method, less memory consumption, high flexibility
  • Disadvantages: The efficiency is somewhat different than FastJson
  • Application scenario: read on demand, large amount of JSON data, complex structure

Jackson:

  • Advantages: high parsing efficiency (the bigger the data, the more obvious), less storage
  • Disadvantage: Document must be fully parsed
  • Application scenario: no need to read on demand, the amount of JSON data is very large

FastJson:

  • Advantages: the fastest parsing speed, surpassing all json libraries; the simplest implementation of parsing
  • Disadvantages:
    The pursuit of "fast" leads to deviation from "standard" and functionality, and the code quality is slightly worse than other types;
    FastJson has requirements for beans, and must have a default constructor, if the bean class does not have a default constructor and is unmodifiable
  • Application scenario: If the amount of data is large, you can consider paging, and use this method when obtaining multiple times. It will perform better in terms of memory usage and efficiency within a certain amount of data.

Note: The above comparison has been sorted out by viewing related blogs, but has not been verified by practice. If there is any error, please correct me!

JSON vs XML

  • performance
    • Storage size:
      JSON is small - XML ​​is large
    • Parsing speed:
      JSON is fast - XML ​​is slow
  • Usage
    • Readable and descriptive:
      JSON is good - XML ​​is bad
    • Parsing complexity:
      JSON simple - XML ​​complex
    • Scalability:
      JSON is bad - XML ​​is good

The above "good" & "bad" etc. are just a comparison of the two

As for who is better and who is worse between XML and JSON, I will not start the battle here. After all, the two have their own advantages and disadvantages in different application scenarios:
simply give a chestnut:

  • For UI description: clearly XML is vastly better than JSON, and the tags in it clearly explain its meaning
  • In network transmission, JSON is better than XML because of its fast parsing speed and small storage size.

Summarize

  • This article summarizes the four ways of parsing JSON in Android
  • For another mainstream data transmission format XML, please move to Android-XML parsing (DOM, SAX, PULL)
  • The author's level is limited, if there are any mistakes or omissions, please correct me.
  • Next, I will also share the knowledge I have learned. If you are interested, you can continue to pay attention to the Android development notes of whd_Alive.
  • I will share technical dry goods related to Android development from time to time, and look forward to communicating and encouraging with you.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326072782&siteId=291194637