Google Gson Concise Tutorials

Source: Internet
Author: User
Tags modifier serialization tojson
Brief Introduction

Gson is a JSON parsing library produced by Google that converts any Java object into a JSON string or converts a JSON string to a corresponding Java object.
The official introduction is as follows:

Gson is a Java library this can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to a equivalent Java object.

Gson can work with arbitrary Java objects including pre-existing objects ' you did not have source code of. maven Dependencies

<dependencies>
    <!--  Gson:java to Json conversion-->
    <dependency>
      <groupid >com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.7 </version>
    </dependency>
</dependencies>
Gson Serialization & deserialization

Serialization&deserialization are accomplished through Gson's Tojson and Fromjson methods. Friendly Tips

This is the main class for using Gson. Gson is typically used by constructing a Gson instance and then invoking (Object) or Tojson (String, Class) m Ethods on it. Gson instances are thread-safe so can reuse them freely across multiple.

Gson are thread-safe (thread-safe) and can be shared between multithreading. Basic Type

Serialization
Gson Gson = new Gson ();
Gson.tojson (1);            ==> 1
Gson.tojson ("ABCD");       ==> "ABCD"
Gson.tojson (new Long);//==>
int[] values = {1};
Gson.tojson (values);       ==> [1]

//deserialization
int one = Gson.fromjson ("1", int.class);
Integer one = Gson.fromjson ("1", integer.class);
Long one = Gson.fromjson ("1", long.class);
Boolean false = Gson.fromjson ("false", boolean.class);
String str = Gson.fromjson ("\" Abc\ "", String.class);
string[] Anotherstr = Gson.fromjson ("[\" Abc\ "]", string[].class);
Simple Objects

1. Serialization of

Class User {
  private long ID;
  private String name;
  private int age;
  private transient int gender;
  User () {
    //No-args constructor
  }
  //Omit Setter/getter method
}

//serialization
User user = new user ();
User.setid (3);
User.setname ("Ricky");
User.setage (a);

Gson Gson = new Gson ();
String JSON = Gson.tojson (user);  
SYSTEM.OUT.PRINTLN (JSON);

Output results:

{"id": 3, "name": "Ricky", "Age": 27}

A few things to note: Serialization objects recommend using basic type properties by default, property values of NULL are ignored when serialized by default, transient-decorated properties are ignored and not exported when serialized and deserialized. 2. Deserialization

Deserialization
Gson Gson = new Gson ();
User obj2 = Gson.fromjson (JSON, user.class);
Complex Objects
Class User {
    private long ID;
    private String name;
    private int age;
    private transient int gender;
    private address address;
    Omit Getter/setter method

}
//serialization
User user = new user ();
User.setid (3);
User.setname ("Ricky");
User.setage (a);
Address = new address ();
Address.setprovince ("Hubei Province");
Address.setcity ("Wuhan City");
Address.setdistrict ("Wuchang District");
User.setaddress (address);
Gson Gson = new Gson ();
String JSON = Gson.tojson (user);  
SYSTEM.OUT.PRINTLN (JSON);

Output results:
{"id": 3, "name": "Ricky", "Age": "The Address": {"province": "Hubei Province", "City": "Wuhan", "District": "Wuchang District"} Array

Gson Gson = new Gson ();
Int[] INTs = {1, 2, 3, 4, 5};
String[] strings = {"abc", "Def", "Ghi"};

Serialization
Gson.tojson (ints);     ==> [1,2,3,4,5]
Gson.tojson (strings);  ==> ["abc", "Def", "Ghi"]

//deserialization
int[] ints2 = Gson.fromjson ("[1,2,3,4,5]", int[].class); 
==> Ints2 would be same as INTs

Gson supports multidimensional array serialization/deserialization. Collection Basic Type

Gson Gson = new Gson ();
collection<integer> ints = lists.immutablelist (1,2,3,4,5);

Serialization
String JSON = Gson.tojson (ints);  ==> JSON is [1,2,3,4,5]

//deserialization
Type collectiontype = new Typetoken<collection<integer >> () {}.gettype ();
collection<integer> ints2 = Gson.fromjson (JSON, collectiontype);
==> Ints2 is same as INTs
Objects Collection
list<user> list = new arraylist<user> ();
        User user = new user ();
        User.setid (1);
        User.setname ("Ricky");
        User.setage (a);
        List.add (user);

        Gson Gson = new Gson ();
        Serialization
        String JSON = Gson.tojson (list);  

        SYSTEM.OUT.PRINTLN (JSON);

        Deserialization
        Type listtype = new typetoken<list<user>> () {}.gettype ();
        List<user> userlist = Gson.fromjson (JSON, listtype);
        System.out.println (userlist);
generic class
Class Foo<t> {
  T value;
}
Gson Gson = new Gson ();
foo<bar> foo = new foo<bar> ();

Type Footype = new typetoken<foo<bar>> () {}.gettype ();
Gson.tojson (foo, footype);

Gson.fromjson (JSON, footype);
Specifies the name of the property serialization

By default, Gson uses the property name as the serialized name, and we can also use the Serializedname annotation to specify a different name for the property than the property name.

Class Person {
    @SerializedName ("first_name")
    private String firstName;
    @SerializedName ("Middle_name")
    private String middlename;
    @SerializedName ("last_name")
    private String lastName;
    private int age;
    Omit Getter/setter method
} person

p = new Person ();
P.setfirstname ("Shark");
P.setmiddlename ("Q");
P.setlastname ("Oneal");
P.setage (a);

Gson Gson = new Gsonbuilder (). Serializenulls (). Create ();
String json = Gson.tojson (p);   {"first_name": "Shark", "Middle_name": "Q", "last_name": "Oneal", "Age": 27}
control Gson serialization and deserialization behavior JSON output Format
Gson Gson = new Gsonbuilder (). setprettyprinting (). Create ();
String jsonoutput = Gson.tojson (someobject);
serializing a null property
Gson Gson = new Gsonbuilder (). Serializenulls (). Create ();
custom serialization and deserialization

Sometimes Gson the default serialization and deserialization will not meet our needs, such as datetime, and we need to customize it now.
Gson allows us to register our custom serializers and deserializers. This section is defined as follows: Json serializers:need to define custom serialization for a object Json deserializers:needed to define custom D Eserialization for a
Type Instance Creators:not needed if No-args constructor is available or
A deserializer is registered


excluding Fields from serialization and deserialization

1, modifier

Import Java.lang.reflect.Modifier;
Gson Gson = new Gsonbuilder ()
    . Excludefieldswithmodifiers (modifier.static)
    . Create ();

2. @Expose annotation

Gson Gson = new Gsonbuilder (). Excludefieldswithoutexposeannotation (). Create ()
Jsonparser

In some cases, if you need to parse the JSON string manually, you can use the Com.google.gson.JsonParser class, as follows:

String json = "{\ first_name\": \ "Shark\", \ "middle_name\": \ "q\", \ "last_name\": \ "oneal\", \ "age\": ";}";

        Jsonparser parser = new Jsonparser ();
        Jsonobject jobj = Parser.parse (JSON). Getasjsonobject ();
        String first_name = Jobj.get ("first_name"). getasstring ();   Shark
        System.out.println (first_name);
reference materials

Https://github.com/google/gson/blob/master/UserGuide.md

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.