Android development: JSON introduction & amp; Gson, AS built-in org. son, and Jackson Parsing

Source: Internet
Author: User

Android development: Introduction to JSON & Gson, detailed analysis of AS built-in org. son and Jackson
Preface

In the previous article, we introduced in detail the methods and comparisons of XML and Its DOM, SAX, and PULL parsing methods. Today, we will introduce JSON, which is also the mainstream data exchange format!

Definition

JavaScript Object Notation, an Object representation of JavaScript, is a lightweight text data exchange format.

Function

Used to mark, store, and transmit data.

Features lightweight text data exchange formats independent of languages and platforms with fast self-descriptive reading and writing speed and simple parsing syntax

JSON Value
-Name/value
-Array
-Object

JSON instance

{"Skill": {
          "web": [
                 {
                  "name": "html",
                  "year": "5"
                 },
                 {
                  "name": "ht",
                  "year": "4"
                 }],
           "database": [
                  {
                  "name": "h",
                  "year": "2"
                 }]
`}}
"Name / value" pairs
Unordered, an object is included with "{}", the name and value are separated by ":", and the objects are separated by ",";
"name": "html"
Object
A JSON object includes multiple name / value pairs, written in curly braces
{"name": "html", "year": "5"}
Array
The array is included with "[]", and the data objects are separated by commas
                 {
                  "name": "html",
                  "year": "5"
                 },
                 {
                  "name": "ht",
                  "year": "4"
                 }]
web and database are both an array

Grammar summary
Array [object {value / pair ""}]

Array contains objects, objects contain values / pairs

JSON parsing
After understanding JSON, it is time to see how to parse JSON data on Android

Analytical method
Android parsing JSON data is similar to XML parsing, there are two main types:
Event-driven and document-driven analysis

Event-driven mainstream method: Gson analysis and Jackson analysis
Gson introduction
-Introduction: Use Google's open source library for analysis
-Parsing method: Based on event-driven, the required JSON data can be parsed by a simple operation by establishing a JavaBean class corresponding to the JSON data according to the required data

Gson analysis
Step 1: Create a JavaBean class corresponding to JSON data (used to store the data to be parsed)
The key to GSON analysis is to write a corresponding javaBean according to the structure in the json data. The rules are:
1. The curly braces of JSON correspond to an object, and there are key and value in the object. The class attribute in JavaBean must have the same name as the key.
2. The square brackets in JSON correspond to an array, so the corresponding in JavaBeanBean is also an array, and the data can have values or objects.
3. If there is only value and no key in the array, it means that it is just a pure array. If there is a value and key in the array, it means an array of objects. A pure array corresponds to the array type in JavaBean. The object array needs to create an internal class in the Bean. The class attribute is the key in the corresponding object. After it is created, an object of this internal class must be created.
4. When an object is nested in an object, an internal class must also be created. Like the object array, the name of this internal class object is the key of the parent object.

Note: The attributes in the JavaBean class do not have to be the same as all the keys in the JSON data. You can fetch the data as needed, that is, what kind of data you want, write the corresponding key attribute, pay attention to the name

There are two JSON documents to illustrate the creation method of creating JavaBean class

Simple JSON data 1 (object)
String json = "{\" id \ ": 1, \" name \ ": \" 小 明 \ ", \" sex \ ": \" 男 \ ", \" age \ ": 18, \" height \ " : 175} ";
Step 1: Create a JavaBean class corresponding to simple JSON data
package scut.learngson;

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 + ",");

    }
}
Complex JSON data (with nesting)
{"translation": ["车"],
  "basic":
    {
      "phonetic": "kɑ?",
      "explains": ["n. car; carriage", "n. (Car) name; (Turkish) Jar; (French, West) Carr; (Cyprus) car"]},
  "query": "car",
  "errorCode": 0,
  "web": [{"value": ["car", "car", "car"], "key": "Car"},
         {"value": ["Concept car", "Concept car", "Concept car"], "key": "concept car"},
         {"value": ["Bumper car", "Bumper car", "Bumper car"], "key": "bumper car"}]
}
Step 1: JavaBean class corresponding to complex JSON data
package scut.httpgson;
import java.util.List;

public class student {
    public String [] translation; // ["car"] array
    public basic basic; // The basic object is nested inside the object, creating a basic inner class object
    public static class basic {// Create internal class
        public String phonetic;
        public String [] explains;
    }
    public String query;
    public int errorCode;
    public List web; // web is an array of objects, create a web internal class object
    public static class wb {
            public String [] value;
            public String key;
        }

    public void show () {
        // Output array
        for (int i = 0; i
Step 2: Download and import the libraries needed by GSON
Don't go over the wall and go to Google's official website, click here

Step 3: Convert with Gson
package scut.learngson;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.google.gson.Gson;

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);
        Gson gson = new Gson ();
        // Create an object of JavaBean class
      Student student = new EntityStudent ();
        String json = "{\" id \ ": 1, \" name \ ": \" 小 明 \ ", \" sex \ ": \" 男 \ ", \" age \ ": 18, \" height \ " : 175} ";
       // Use GSON method to convert JSON data into a single class entity
        student = gson.fromJson (json, Student.class);
       // Call the student method to display the parsed data
        student.show ();
      // Convert Java collection to json
        String json2 = gson.toJson (List); System.out.println (json2);
    }
}
to sum up
It can be seen that the key to parsing using the GSON method is to write a corresponding javaBean according to the structure in the json data, and the parsing process is very simple:

JavaBean object = gson.fromJson (son, javaBean class class name.class);
Jackson analysis
Analysis principle: Based on event-driven, the same as GSON, first create a JavaBean class corresponding to JSON data to parse out the required JSON data through a simple operation. However, unlike Gson parsing, GSON can parse on demand, that is, the created JavaBean class does not necessarily completely cover the JSON data to be parsed, and attributes are created on demand, but Jackson parses the corresponding JavaBean must put the Json data inside All keys have a correspondence, that is, all data in JSON must be parsed out, and cannot be parsed on demand. But Jackson's resolution speed and efficiency are higher than GSON

Core code

JSON data
{"student":
          [
           {"id": 1, "name": "小 明", "sex": "Male", "age": 18, "height": 175, "date": [2013,8,11]},
           {"id": 2, "name": "Little Red", "sex": "Female", "age": 19, "height": 165, "date": [2013,8,23]},
           {"id": 3, "name": "小 强", "sex": "Male", "age": 20, "height": 185, "date": [2013,9,1]}
          ],
  "grade": "2"
}
Step 1: Create the corresponding javaBean:
The corresponding rules for establishing javaBean are the same as GSON

package scut.learnjackson;

import java.util.ArrayList;
import java.util.List;
class test {
    private List student = new ArrayList ();

    private int grade;

    public void setStudent (List student) {
        this.student = student;
    }
    public List 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 Step 2: Use Jackson method for analysis
package scut.learnjackson;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import org.codehaus.jackson.map.ObjectMapper;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView (R.layout.activity_main);
        ObjectMapper objectMapper = new ObjectMapper ();
        try {
            InputStreamReader isr = new InputStreamReader (this.getClass (). GetClassLoader (). GetResourceAsStream ("assets /" + "student.json"), "utf-8");
            // Get json file from assets
            BufferedReader bfr = new BufferedReader (isr);
            String line;
            StringBuilder stringBuilder = new StringBuilder ();
            while ((line = bfr.readLine ())! = null) {
                stringBuilder.append (line);
            } // Convert JSON data to strings
            System.out.println (stringBuilder.toString ());
            System.out.println (tes.tostring ());

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

    }


}

Document-based analysis
Mainstream method: Android Studio comes with org.son parsing. Parsing method: based on document-driven, similar to XML DOM parsing method, first read all files into memory, then traverse all data, and then retrieve the desired data as needed.
JSON data to be parsed:


{
"student": [
            {"id": 1, "name": "小 明", "sex": "Male", "age": 18, "height": 175},
            {"id": 2, "name": "Little Red", "sex": "Female", "age": 19, "height": 165},
            {"id": 3, "name": "小 强", "sex": "Male", "age": 20, "height": 185}
          ],
"cat": "it"
}

Read student.son in the local assets folder and parse


package scut.learngson;

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 {
            // Get json file from assets
            InputStreamReader isr = new InputStreamReader (this.getClass (). GetClassLoader (). GetResourceAsStream ("assets /" + "student.json"));
            // Byte stream to character stream
           BufferedReader bfr = new BufferedReader (isr);
            String line;
            StringBuilder stringBuilder = new StringBuilder ();
            while ((line = bfr.readLine ())! = null) {
                stringBuilder.append (line);
            } // Convert JSON data to strings
            JSONObject root = new JSONObject (stringBuilder.toString ());
            // Acquire key value information based on key name
            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 (); // Close the stream in turn
            }
        } catch (IOException e) {
            e.printStackTrace ();
        } catch (JSONException e) {
            e.printStackTrace ();
        }

    }
}

GSON, Jackson, Android Studio comes with org.son analysis of three types of comparison
Android Studio comes with org.son

-Principle: driven by documents

-Features:

Advantages: none

Disadvantages: When parsing the XML file, the content of the entire XML file will be parsed into a tree structure and stored in memory and new objects will be created, which will consume time and memory, the parsing speed and efficiency are slow, and the parsing method and performance are completely defeated


GSON method

-Principle: Event-driven

-Features:

Advantages: Simple analysis method, high analysis efficiency, less storage, high flexibility

- Usage scenarios

Applicable to occasions where large JSON documents need to be processed and the structure of JSON documents is complex


Jackson way

-Principle: Event-driven

-Features:

Advantages: The highest analysis efficiency, especially in the case of large data volume, the advantage is particularly obvious, and the occupation is small

Disadvantages: 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 method are complicated;

- Usage scenarios

Applicable to occasions that need to process very large JSON documents, do not need to parse JSON documents on demand, and have high performance requirements


Comparison with XML parsing
For the data exchange format, which is also the mainstream, JSON has a smaller file size, simpler parsing method, and faster reading and writing speed than XML. Therefore, JSON must be your first choice in the selection of data exchange format.


to sum up
This article gives a comprehensive introduction to the current mainstream data transmission format JSON. Next, we will introduce another less mainstream but very powerful data transmission format-Google's Protocol Buffer. If you are interested, you can continue to follow Carson_Ho's blog!



Also welcome to follow Carson_Ho's brief book! Share the dry goods of "Android Development" from time to time! )

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.