Android Development: JSON introduction and the most comprehensive parsing method (Gson, as with Org.json, Jackson parsing)

Source: Internet
Author: User

Objective

Today, we introduce the current mainstream data interchange Format-json!

Same as mainstream for data Interchange Format-xml, if interested can read I write XML and its DOM, SAX, pull parsing method and contrast

Directory
Introduction to JSON & Introduction to parsing methods. PNG definition

The object notation for JavaScript object Notation,javascript is a lightweight text data interchange format.

Role

Used for tagging, storing, and transmitting data.

Characteristics
    • Lightweight Text Data Interchange Format
    • Independent of language and platform
    • Self-descriptive
    • Fast read and write speed, simple parsing
Grammar

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 with "{}" includes, between the name and value by ":" Separated by "," between objects;
      "name":"html"
    • Object
      A JSON object consists of multiple name/value pairs, written in curly braces

      { "name":"html","year":"5"}
    • Array
      Arrays are included with "[]", data objects are separated by commas

                     {                "name":"html",                "year":"5"               },               {                "name":"ht",                "year":"4"               }]

      Both the Web and database are an array

Grammar summary

Array [Object {value/pair '}]

Array contains objects, objects contain values/pairs

JSON parsing

After understanding the JSON, it's time to look at how to parse the JSON data on Android

Parsing methods

The way that Android parses JSON data is similar to XML parsing, with two main types:
Event-driven and document-driven parsing

Event-driven
    • Mainstream approach: Gson parsing and Jackson parsing

Gson Introduction

    • Introduction: Using Google's Open Source library for parsing
    • Parsing mode: Based on event-driven, according to the data required by the creation of a corresponding to the JSON data JavaBean class can be simple operation to resolve the required JSON data
Gson parsing

Step 1: Create a JavaBean class that corresponds to the JSON data (used to store data that needs to be parsed)
The key to Gson parsing is to write a corresponding javabean based on the structure of the JSON data, the rules are:

    1. The curly braces of the JSON correspond to an object with the key and value (value) inside the object. The class property inside the JavaBean must have the same name as key.
    2. The square brackets of the JSON correspond to an array , so there is an array in the Javabeanbean, and the data can have values or objects.
    3. If there is only a value in the array without a key, it means that it is only a pure array, and if there is a value with a key, then it is an object array. The pure array corresponds to the array type inside the JavaBean, the object array is to create an inner class within the bean, the class attribute is the key within the corresponding object, and the object of the inner class is created, and the name corresponds to the array name.
    4. When nesting objects inside an object, create an inner class, like an object array, whose name is the parent object's key

Note: The attributes in the JavaBean class do not have to be all the same as all keys in the JSON data, you can take the data as needed, that is, what kind of data you want, the corresponding key attribute is written, note that the name must correspond

Here are two JSON documents to illustrate how to create a JavaBean class

Simple JSON data 1 (object)
String json = "{\"id\":1,\"name\":\"小明\",\"sex\":\"男\",\"age\":18,\"height\":175}";
Step 1: Create a simple JSON data corresponding to the JavaBean class
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.) {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. 汽车;车厢","n. (Car)人名;(土)贾尔;(法、西)卡尔;(塞)察尔"]},  "query":"car",  "errorCode":0,  "web":[{"value":["汽车","车子","小汽车"],"key":"Car"},         {"value":["概念车","概念车","概念汽车"],"key":"concept car"},         {"value":["碰碰车","碰撞用汽车","碰碰汽车"],"key":"bumper car"}]}
Step 1: Complex JSON data corresponding to the JavaBean class
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{//Building internal class public String phonetic;    Public string[] explains;    } public String query;    public int errorCode;            Public list<wb> web;            The web is an array of objects, creating a Web inner class object public static Class Wb{public string[] value;        Public String key; public void Show () {//output array for (int i = 0;i<translation.length;i++) {System.out.print        ln (translation[i]);        }//Output internal class object System.out.println (Basic.phonetic);        Output inner class array 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); }    }    }

OK, do you think it's complicated to convert from JSON text data to JavaBean entity classes? In fact, there is a simple method, please use the online JSON string to the Java entity class, haha please do not hit me, continue to look down!

Step 2: Download and import the required libraries for Gson

Don't fq 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 the JavaBean class Student Student = new Entitystudent ();       String json = "{\" id\ ": 1,\" name\ ": \" Xiao Ming \ "," sex\ ": \" male \ ", \" age\ ": 18,\" height\ ": 175}";       Use the Gson method to convert the JSON data to a single class entity student = Gson.fromjson (Json,student.class);      Call the student method to demonstrate the parsed data student.show ();        Converts a Java collection to json String Json2 = Gson.tojson (List);    System.out.println (Json2); }}
Summarize

As you can see, the key to parsing using the Gson method is to write a corresponding javabean based on the structure of the JSON data, and the parsing process is simple:

JavaBean对象 = gson.fromJson(son,javaBean类类名.class);

Jackson parsing

    • Parsing principle: Based on event-driven, the same as Gson, first create a corresponding to the JSON data of the JavaBean class can be simple operation to resolve the required JSON data. But unlike Gson parsing, Gson can be parsed on demand, that is, the JavaBean class created does not necessarily completely cover the JSON data to be parsed, creating attributes on demand, but Jackson parsing the corresponding JavaBean must correspond to all the keys in the JSON data. That is, the data inside the JSON must be parsed out and not parsed as needed. but Jackson's analytical speed and efficiency are higher than Gson.

    • Core code

JSON data
{"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"}
Step 1: Establish 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<stu> Studen    t = 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.) {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: Use the Jackson method to parse
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 (Bu        Ndle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Objectmapper objectmapper = new Objectmapper (); try {inputstreamreader ISR = new InputStreamReader (This.getclass (). getClassLoader (). getResourceAsStream ("Asset            s/"+" 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); }//converts the JSON data into a string System.out.println (StringBuilder.ToString ());        System.out.println (Tes.tostring ());        } catch (IOException e) {e.printstacktrace (); }    }}
Based on the document-driven parsing method
    • Mainstream way: Android studio comes with Org.json parsing
    • Parsing: Document-driven, XML-like parsing of the DOM, first read all the files into memory, then traverse all the data, and then retrieve the desired data as needed.

JSON data that needs to be parsed:

{"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"}

Read the 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 (Bu        Ndle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Entitystudent student = new Entitystudent (); try {//Gets the JSON file from assets InputStreamReader ISR = new InputStreamReader (This.getclass (). getClassLoader            (). getResourceAsStream ("assets/" + "Student.json"));            Byte stream character streams BufferedReader bfr = new BufferedReader (ISR);            String Line;            StringBuilder StringBuilder = new StringBuilder ();            while (line = Bfr.readline ())!=null) {stringbuilder.append (line); }//convert JSON data to string JSONOBJECT root = new Jsonobject (stringbuilder.tostring ());            Gets the key value information System.out.println ("Root:" +root.getstring ("Cat") based on the key name;            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 ();//Turn Off Stream}} catch (IOException e) {e.printstacktrace ();        } catch (Jsonexception e) {e.printstacktrace (); }    }}
Gson, Jackson, Android Studio comes with Org.son parsing three kinds of way comparison

Android Studio comes with Org.json

    • Principle: Document-driven
    • Characteristics:
      Pros : None
      disadvantage : Parsing an XML file will parse the contents of the entire XML file into a tree structure in memory and create new objects, comparing time and memory consumption, parsing speed and efficiency, parsing and performance Gson

Gson Way

    • Principle: Event-driven
    • Characteristics:
      Advantages : Simple analytic method, high resolution efficiency, small deposit, high flexibility
    • Usage Scenarios
      Suitable for situations where large JSON documents need to be processed and the structure of the JSON document is complex

Jackson Way

    • Principle: Event-driven
    • Characteristics:
      Advantages : The analytic efficiency is highest, in the case of large data volume, the advantages are particularly obvious, occupying less
      disadvantage : The document must be fully parsed, if you want to parse on demand can be split json to read, operation and parsing method is complex;
    • Usage Scenarios
      Ideal for applications that require processing of very large JSON documents, no need for on-demand parsing of JSON documents, and high performance requirements
Comparison with XML parsing

For the same mainstream data Interchange format, JSON has a smaller size than a Xml,json document, a simpler parsing method, and faster read and write, so JSON must be your first choice in Data Interchange Format selection.

Android Development: JSON introduction and the most comprehensive parsing method (Gson, as with Org.json, Jackson parsing)

Related Article

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.