Java JSON transformation Class Library Gson basic Use tutorial _java

Source: Internet
Author: User
Tags static class tojson

Gson (Github:https://github.com/google/gson) is a Java class library that Google provides to map between Java objects and JSON data. You can turn a JSON string into a Java object, or vice versa.
The most important objects in Gson are 2 Gson and Gsonbuilder.
Gson has 2 basic methods.
(1) Tojson () – Convert Java objects to JSON
(2) Fromjson () – Convert JSON to Java objects

Writing entity classes:

public class People {
String name;
int age;
Boolean setname;
Public String GetName () {return
name;
Public
void SetName (String name) {
this.name = name;
public
int Getage () {return age
;
Public
void Setage (int age) {
this.age = age;
Public
Boolean getsetname () {return
setname;
} public
void Setsetname (Boolean setname) {
this.setname = SetName;
@Override public
String toString () {return
' name= ' + name + ' age= ' + age + ' setname= ' +setname  ;
}
}

Writing test class Gsontest

Import Com.google.gson.ExclusionStrategy;
Import com.google.gson.FieldAttributes;
Import Com.google.gson.Gson;
Import Com.google.gson.GsonBuilder;
/**
 * Convert Java object to JSON.
 *
/public class Gsontest {public
static void Main (string[] args) {
people P = new people ();
P.setage (a);
P.setname ("people");
P.setsetname (true);
Gson Gson = new Gson ();
System.out.println (Gson.tojson (P));
}
}

Output results:

{' name ': ' People ', ' age ': ' SetName ': true}

This is just the simplest use of gson. How do we do this if we need to convert a bool-type attribute setname into JSON without converting it?

Looking for half a day in the Gson bag, found that the Com.google.gson package has such an interface: Exclusionstrategy, although not clear what is doing, but according to the name, you can infer that this interface is used to set the Gson conversion of the exclusion strategy, So at the official website http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/ Index.html checked the interface and found that as long as the interface was implemented and the object of the implementation class was Gson, Gson would filter out the specified class or attribute when converting to JSON. So the following code is available:

Import Com.google.gson.ExclusionStrategy;
Import com.google.gson.FieldAttributes;
Import Com.google.gson.Gson;
Import Com.google.gson.GsonBuilder;
 /** * Convert Java object to JSON, skip specific fileds.
    */public class Gsontest {public static void main (string[] args) {people p = new people ();
    P.setage (20);
    P.setname ("people");
    P.setsetname (TRUE);
    Exclusionstrategy excludestrategy = new Setterexclusionstrategy ();
    Gson gson1 = new Gsonbuilder (). Setexclusionstrategies (Excludestrategy). Create ();
    Gson gson2 = new Gson ();
    String json1 = Gson1.tojson (p);
    String json2 = Gson2.tojson (p);
    System.out.println (Json1);

    System.out.println (Json2);
    People p1 = Gson1.fromjson (Json1, People.class);
    People p2 = Gson2.fromjson (Json2, People.class);
    System.out.println (p1);
  System.out.println (p2); private static class Setterexclusionstrategy implements Exclusionstrategy {public boolean shouldskipclass (class& lt;? ";
    Clazz) {return false;
    public boolean Shouldskipfield (FieldAttributes f) {return F.getname (). StartsWith ("set");

 }   } }

Originally, there are two ways to create a Gson object: New Gson () means to create a Gson object using the default configuration, and if you create it with the Gsonbuilder.create () method, you can customize some settings. This is primarily to make the created Gson more suitable for certain situations. The first blue code in the example above creates a Gson object that has a filtered configuration of a property that starts with the word "set" (if a type is filtered out, the shouldskipclass of the Exclusionstrategy Interface is overridden) (class< ?> Clazz) method, if you need to filter out a variety of situations, you can create several Exclusionstrategy implementation class objects and set them up when you create the Gson object, so in this case, when you convert the People object to JSON, Property SetName will be filtered out. Because there is no attribute setname in the Json1, the Boolean setname has no value when Json1 is deserialized into a people object, so the Boolean type default value is taken when printing. The following results are available:

{' name ': ' People ', ' age ':}
{' name ': ' People ', ' age ': ' SetName ': true}
Name=people age=20 setname=false
name=people age=20 setname=true

Gson also supports the use of annotations, in the Com.google.gson.annotation package, there are several annotations expose, serializedname, since and until, each with their respective roles, the following official examples are used to introduce the commonly used annotations:

Expose:

This annotation acts on attributes, indicating that this property will be exposed to the Gson object when serialized and deserialized. This annotation is valid only if the Gsonbuilder.excludefieldswithoutexposeannotation () method is created and invoked in Gsonbuilder mode when creating the Gson object. Here is an example of how @expose annotations are used:

public class User {
 @Expose private string firstName;
 @Expose (serialize = False) private string lastName;
 @ Expose (serialize = false, Deserialize = false) private String EmailAddress;
 private String password;
}

If you create a Gson object in the form of New Gson (), the Tojson () method and the Fromjson () method will manipulate these 4 properties when serializing and deserializing. However, if you use the Gson Gson = new Gsonbuilder (). Excludefieldswithoutexposeannotation (). Create () creates the Gson object, Gson () and The Fromjson () method excludes the password field because the password field is not marked by the annotation @Expose. This Gson object also excludes LastName and EmailAddress fields because the annotation @expose property serialize is set to false. Similarly, Gson will remove the EmailAddress field when deserializing, because deserialize is set to false.

Serializedname:

This annotation acts on attributes, indicating that when serialized into JSON, the attribute needs to serialize the name to the value specified by the Value property of the annotation.

This annotation will overwrite any fieldnamingpolicy, including the default naming policy. Here is an example of how @serializedname annotations are used:

public class Someclasswithfields {
 @SerializedName ("name") private final string Somefield;
 Private final string Someotherfield;
 Public Someclasswithfields (String A, string b) {
  This.somefield = A;
  This.someotherfield = b;
 }
}

The following code shows the results of serialization of this test class:

Someclasswithfields objecttoserialize = new Someclasswithfields ("A", "B");
Gson Gson = new Gson ();
String jsonrepresentation = Gson.tojson (objecttoserialize);
System.out.println (jsonrepresentation);

The results of the execution are:

{' name ': ' A ', ' Someotherfield ': ' B '}

This shows that the attribute "Somefield" has been serialized to "name".

Note: The property name specified in @serializedname value must be a valid JSON property name.

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.