Gson use in detail (Android Essentials, Fast development efficiency)

Source: Internet
Author: User

Gson use in detail (Android Essentials, Fast development efficiency)Next I would like to strongly recommend to you a Google's official recommended JSON parsing library Gson. After mastering it, in the future development will be reduced a lot of code, the use of very convenient.
Overview:
Gson is a Java library, not only can it convert a Java object into JSON format, it can also convert a JSON-formatted string into a relative Java object. Gson applies to all Java objects, even those that you do not know the source code for.

Gson's goal
    1. Provides easy-to-use methods such as toString () to construct methods to convert Java to JSON and reverse conversions.
    2. Provides conversion of non-modifiable objects in the village to JSON and reverse conversions.
    3. The customary representation of the provided object
    4. Support for arbitrary complex objects
    5. Generate robust, readable JSON input
With some official instructions, you can see that Gson is a very good tool for JSON parsing and transformation. A short sentence is:convenient and fast and powerful。
Having talked so much about its benefits, then start to teach you how to use it in your own projects.
First step: How to add Gson Library 1, first, in their own Android studio project to add the Gson library, right-click the app to select Open module settings,
2, select the app, then click Dependencies, click on 3 steps in the library dependency (dependent libraries)


3, in 1 refers to the pop-up box in the Gson, then click on the 2 refers to the collection, and then the following will appear the latest Gson library, click OK

4, click OK, Gson Library appears in the dependency, this time also have to click 2 refers to the OK button.

5, the last view Build.gradle to see if Gson Library has been added successfully, such as 2 refers to the place, now you can see the official Google Gson Library is added to the project. Next, you can use Gson in your code. Congratulations, you can finally reduce the tedious JSON parsing code.


Step two: How to use the Gson library
It explains in detail how to add a dependent library to your project, and successfully added the Gson library, and then tell me how to use it in detail. The first scenario: Converting a Java object to a JSON format first build an entity class, named child as follows:
<pre class= "java" name= "code" >package com.world.hello.gsonexample;import Java.util.arraylist;import java.util.hashmap;/** * Child entity class * Created by Chengguo on 2016/3/21.    */public class Child {private int id;    private String name;    Private String sex;    private int age;    Children's toys private arraylist<string> toys;    Children's toys Map private hashmap<string, string> toysmap = new hashmap<string, string> ();    Children's books private arraylist<book> books = new Arraylist<book> ();    Public arraylist<book> Getbooks () {return books;    } public void Setbooks (Arraylist<book> books) {this.books = books;    } public hashmap<string, String> Gettoysmap () {return toysmap;    } public void Settoysmap (hashmap<string, string> toysmap) {this.toysmap = Toysmap;    } public arraylist<string> Gettoys () {return toys; } public void Settoys (Arraylist<string> toys) {This.toys = toys;    } public int getId () {return id;    } public void setId (int id) {this.id = ID;    } public String GetName () {return name;    } public void SetName (String name) {this.name = name;    } public String Getsex () {return sex;    public void Setsex (String sex) {this.sex = sex;    } public int Getage () {return age;    public void Setage (int.) {this.age = age; }}
Package com.world.hello.gsonexample;/** * Book entity class * Created by Chengguo on 2016/3/21. */public class Book {    private String name;    Private String Price;    Public String GetName () {        return name;    }    public void SetName (String name) {        this.name = name;    }    Public String GetPrice () {        return price;    }    public void Setprice (String price) {        This.price = Price;    }}
whichThe child class contains a list collection of basic data types, basic types, a map collection of basic types, and a list collection containing object types. Believe that so many of the data types, basically can show its corresponding processing function. The next step is to add the Java code to the data, as follows:
Package Com.world.hello.gsonexample;import Android.os.bundle;import android.support.v7.app.AppCompatActivity; Import Android.util.log;import com.google.gson.gson;import Java.util.arraylist;import java.util.HashMap;public        Class Mainactivity extends Appcompatactivity {@Override protected void onCreate (Bundle savedinstancestate) {        Super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Gson Gson = new Gson ();        Child child = new Child ();        Child.setid (1);        Child.setage (10);        Child.setname ("Child A");        Child.setsex ("male");        arraylist<string> toys = new arraylist<string> ();        Toys.add ("trolley");        Toys.add ("Pikachu");        Toys.add ("Ultraman");        Toys.add ("Naruto");        Child.settoys (toys);        hashmap<string, string> toysmap = new hashmap<string, string> ();        Toysmap.put ("1", "Trolley 2");        Toysmap.put ("2", "Pikachu 2");        Toysmap.put ("3", "Ultraman 2"); Toysmap.put ("4", "Naruto 2");        Child.settoysmap (TOYSMAP);        arraylist<book> books = new Arraylist<book> ();            for (int i = 0; i < 3; i++) {Book book = new book ();            Book.setname ("Grimm's Fairy tale" + i);            Book.setprice ("Price:" + i + "$");        Books.add (book);        } child.setbooks (books);    LOG.I ("Child", Gson.tojson (child)); }}
Output Result:
{"Age    ": Ten,    "books": [        {            "name": "Grimm fairy Tale 0",            "price": "Prices: 0$"        },        {            "name": "Grimm fairy tale 1",            "Price": "Prices: 1$"        },        {            "name": "Grimm fairy Tale 2",            "price": "Prices: 2$"        }    ],    "id": 1,    "name": "Child A",    "sex": "Male",    "Toys": [        "Dolly",        "Pikachu",        "Ultraman",        "Naruto"    ],    "Toysmap": {        "1": "Trolley 2",        "2 ":" Pikachu 2 ",        " 3 ":" Ultraman 2 ",        " 4 ":" Naruto 2 "    }}
It's really simple, just two lines of code.
Gson Gson = new Gson (); Gson.tojson (object); Isn't it very simple.
All right, the above is using Gson to convert the object to JSON. There are various data types of packages that are believed to meet the needs. It is often only when data is submitted to the server that the object needs to be converted to a JSON data format.

    second case: converting a JSON-formatted string into a relative Java object
Android Development for network data transmission, the current basic is the use of JSON data format, we usually do is to first look at the background data have what properties, and then define this class, such as: Backstage
Passed a child JSON data, we see an id attribute, and then go to the child this class to define the id attribute, it is not very time-consuming, now, after Gson, everything becomes very simple. Let's see how we can quickly generate a child object based on the JSON generated in the first case.
1. First, we define a CHILD2 this entity class based on the JSON data format or business needs. Then right click on Generate (shortcut key Alt+insert);
          
2, then click Gsonformat (only the project successfully added Gson library will have gsonformat this option);


3, then pop up a window, and then in this window, the network gets the JSON data paste into this, and then click OK.


4. The following interface appears in the new Window that pops up, where you can modify the data type (datatype) and Field name (property name). here The age is changed to Age2, only for demonstration. There is also the case thatwhen the value is null (NULL), such as having the age property, but when the age returned is null, and after you have communicated with the background developer, you can see that this is an int type, and you will be able to set the data type to int for the date. This allows you to modify the data type of the property yourself.



after clicking OK, the entity class for Child2 is created automatically for us, as follows:

Package Com.world.hello.gsonexample;import Com.google.gson.annotations.serializedname;import java.util.List;/** * Created by Chengguo on 2016/3/21. */public class Child2 {/** * age:10 * Books: [{"Name": "Grimm fairy Tale 0", "Price": "Prices: 0$"},{"name": "Grimm fairy Tale 1", "Price": "Prices      : 1$ "},{" name ": Grimm fairy Tale 2", "Price": "Prices: 2$"}] * id:1 * Name: Child A * sex: Male * toys: ["Trolley", "Pikachu", "Ultraman", "Naruto"]    * Toysmap: {"1": "Trolley 2", "2": "Pikachu 2", "3": "Ultraman 2", "4": "Naruto 2"} */@SerializedName ("age") private int age2;    private int id;    private String name;    Private String sex;    /** * 1: Trolley 2 * 2: Pikachu 2 * 3: Ultraman 2 * 4: Naruto 2 */private Toysmapbean toysmap;    /** * Name: Grimm fairy tale 0 * Price: Prices: 0$ */private list<booksbean> books;    Private list<string> toys;    public int GetAge2 () {return age2;    } public void SetAge2 (int age2) {this.age2 = Age2;    } public int getId () {return id; } public void setId (int id) {this.id = ID;    } public String GetName () {return name;    } public void SetName (String name) {this.name = name;    } public String Getsex () {return sex;    public void Setsex (String sex) {this.sex = sex;    } public Toysmapbean Gettoysmap () {return toysmap;    } public void Settoysmap (Toysmapbean toysmap) {this.toysmap = Toysmap;    } public list<booksbean> Getbooks () {return books;    } public void Setbooks (List<booksbean> books) {this.books = books;    } public list<string> Gettoys () {return toys;    } public void Settoys (List<string> toys) {this.toys = toys;        public static class Toysmapbean {@SerializedName ("1") private String value1;        @SerializedName ("2") private String value2;        @SerializedName ("3") private String value3;        @SerializedName ("4") private String value4; PuBlic String getValue1 () {return value1;        } public void SetValue1 (String value1) {this.value1 = value1;        } public String GetValue2 () {return value2;        } public void SetValue2 (String value2) {this.value2 = value2;        } public String GetValue3 () {return value3;        } public void SetValue3 (String value3) {this.value3 = Value3;        } public String GetValue4 () {return value4;        } public void SetValue4 (String value4) {this.value4 = Value4;        }} public static class Booksbean {private String name;        Private String Price;        Public String GetName () {return name;        } public void SetName (String name) {this.name = name;        } public String GetPrice () {return price; } public void Setprice (String price) {This.price= Price; }    }}

you will find that gson the objects in the internal collection into the Child2 class, where we can create the Bookbean class manually to the outside, and it is very convenient to eliminate the tedious operation of creating it.       it explains how to create objects based on the results returned by the server. The following explains how to use Gson to convert the results returned by the server into a solid object.
public void Onresponse (String response) {              //successful acquisition of network JSON data             Child2 child2 = Gson.fromjson (response, Child2.class) ;}
Just a word to get the Child2 object, so that less than dozens of rows, more than hundreds of thousands of lines of JSON parsing code. Above is the acquisition of an object data, followed by the list data.
list<child2> child2list = Gson.fromjson (response, New typetoken<list<child2>> () {}.getType ());


You can see that the code above uses TypeToken, which is a data type converter provided by Gson, and it is a code that can convert JSON data into list data and support various data collection type conversions.

Note: When the property value is int and its data in JSON is empty, the Gson resolution defaults to 0;

When the property value is string, and its data in JSON is NULL, the Gson resolution defaults to the string "null";

The basic use of Gson is so much. Hope to help you with your study.













Gson use in detail (Android Essentials, Fast development efficiency)

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.