@

  • 1. Create Gson instance
    • 1.1, new Gson ()
    • 1.2, GsonBuilder. The build ()
  • Java object –>JSON
  • JSON–>Java object
  • 4. Output beautifully
  • JSON array –> Java array/list
    • 5.1, JSON array –>Java object
    • 5.2, the JSON array – > List
    • JSON array–> member variables
  • 6, JSON < — – > Set
    • 6.1, the Set – > JSON
    • 6.2, JSON – > Set
  • 7, Null value processing
    • 7.1. How do I allow null values in serialization
  • Version support
    • 8.1 @since Annotations
    • 8.2. How do I write versioned classes using the @since annotation
    • 8.3. Create a Gson instance with version support
    • 8.4, the instance,
  • 9. Change the field name mapping between Java objects and JSON
    • 9.1, @ SerializedName
    • 9.2. Change field names during serialization
    • 9.3. Change the field name when deserializing
  • 10. Exclude or ignore fields
    • 10.1, @expose
    • 10.2. Exclude fields with modifiers
    • 10.3. Exclusion Strategy
  • 1, GsonBuilder. SetPrettyPrinting () – beautifully printed JSON
  • 2, FieldNamingPolicy
    • 2.1, FieldNamingPolicy. IDENTITY
    • 2.2, FieldNamingPolicy LOWER_CASE_WITH_DASHES
    • 2.3, FieldNamingPolicy LOWER_CASE_WITH_DOTS
    • 2.4, FieldNamingPolicy LOWER_CASE_WITH_UNDERSCORES
    • 2.5、 FieldNamingPolicy.UPPER_CAMEL_CASE
    • 2.6, FieldNamingPolicy UPPER_CAMEL_CASE_WITH_SPACES
  • 3, GsonBuilder. SerializeNulls serialize () – a null value
  • 4, GsonBuilder. SetExclusionStrategies ()
  • 5. Gsonbuilder.setlenient () — Loose JSON syntax rules
  • 1, the JsonReader
  • 2, Tokens
  • Create GSON JsonReader
  • Read the JSON stream
  • Create JsonParser
  • 2. Convert JSON
  • JsonElement, JsonObject, and JsonArray
  • 4. Gson JsonParser example
  • Get the JsonObject from fromJson()
  • Iterate over the JSON tree structure
  • 1. Custom serialization
    • 1.1. JsonSerializer interface
    • 1.2. Custom serialization examples
  • 2. Custom deserialization
    • 2.1. JsonDeserializer interface
    • 2.2. Custom deserialization examples


A list,

Gson (also known as Google Gson) is an open source Java library released by Google. It is mainly used to serialize Java objects into JSON strings or deserialize JSON strings into Java objects.

Gson official website: Gson SOURCE address: Google/Gson


Second, the reliance on

Import dependencies using Maven:

    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.8.5</version>
    </dependency>
Copy the code

Gradle import dependencies:

compile group: 'com.google.code.gson', name: 'gson', version: '2.8.5'
Copy the code


Three, basic usage


1. Create Gson instance

The first step in using Gson is to create a Gson object. There are two ways to create a love You Gson object:

  • Use the new Gson ()
  • Create an instance of GsonBuilder using the create() method

1.1, new Gson ()

The following is an example:

Gson gson = new Gson();
Copy the code


1.2, GsonBuilder. The build ()

The following is an example:

GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
Copy the code


Java object –>JSON

This entity class is used below:

public class Employee {
 private int id;
 private String firstName;
 private String lastName;
 private String email;
 // omit getter/setter, constructor, toSting method } Copy the code

Serialization in Gson converts A Java object to its JSON representation. To serialize, you first need a Gson object that can handle the transformation. Next, you need to call the function toJson() method and pass in the Employee object.

  Employee emp = new Employee(1001."Lokesh"."Gupta"."[email protected]");
  
  Gson gson = new Gson();
  
  String jsonString = gson.toJson(emp);
  System.out.println(jsonString); Copy the code

Running results:

Insert a picture description here


JSON–>Java object

Antisequencing in Gson refers to converting JSON strings into Java objects. To deserialize, we need to call the fromJson() function using the Gson object and pass in two parameters, the JSON string and the desired Java type, after parsing.

  String jsonString = "{'id':1001, 'firstName':'Lokesh', 'lastName':'Gupta', 'email':'[email protected]'}";
        
  Gson gson = new Gson();
   
  Employee empObject = gson.fromJson(jsonString, Employee.class);
  System.out.println(empObject); Copy the code

Running results:

4. Output beautifully

By default, Gson prints JSON in compact format, meaning there will be no Spaces between field names and their values, object fields, objects in arrays in JSON output, and so on.

{"id":1."firstName":"Lokesh"."lastName":"Gupta"."emailId":"[email protected]"}
Copy the code

However, this compact JSON can be difficult to read. Therefore, GSON provides a nice print option where you can print JSON to make it easier to read.

  Gson gson = new GsonBuilder()
                .setPrettyPrinting()
                .create();
  
  Employee employeeObj = new Employee(1."Lokesh"."Gupta"."[email protected]");
  System.out.println(gson.toJson(employeeObj)); Copy the code

Running results:



JSON array –> Java array/list

5.1, JSON array –>Java object

Users. Json:

[
    {
      "name": "Alex".      "id": 1
    },
 {  "name": "Brian". "id": 2  },  {  "name": "Charles". "id": 3  } ] Copy the code

User. Java:

public class User 
{
    private long id;
    private String name;
     
 public long getId(a) {  return id;  }  public void setId(long id) {  this.id = id;  }  public String getName(a) {  return name;  }  public void setName(String name) {  this.name = name;  }   @Override  public String toString(a) {  return "User [id=" + id + ", name=" + name + "]";  } } Copy the code

Deserialize a JSON array into a Java object array:

String userJson = "[{'name': 'Alex','id': 1}, "
                + "{'name': 'Brian','id':2}, "
                + "{'name': 'Charles','id': 3}]";
         
Gson gson = new Gson(); 
 User[] userArray = gson.fromJson(userJson, User[].class);  for(User user : userArray) {  System.out.println(user); } Copy the code

Running results:


5.2, the JSON array – > List

Deserialize the JSON array as root — to the Java object list:

  String userJson = "[{'name': 'Alex','id': 1}, " + "{'name': 'Brian','id':2}, " + "{'name': 'Charles','id': 3}]";

  Gson gson = new Gson();

  java.lang.reflect.Type userListType = new TypeToken<ArrayList<User>>() {
 }.getType();   ArrayList<User> userArray = gson.fromJson(userJson, userListType);   for (User user : userArray) {  System.out.println(user);  }  Copy the code

Running results:

Insert a picture description here


JSON array–> member variables

If the Json array is a non-root object, Gson can parse the Json array as a member variable. We can use the fromJson() method in the usual way to parse the JSON array into the desired Java array or list.

department.json:

{
    "id"    : 1.    "name"  : "HR".    "users" : [
        {
 "name": "Alex". "id": 1  },  {  "name": "Brian". "id": 2  },  {  "name": "Charles". "id": 3  }  ] Copy the code


5.3.1 Array type member variables

Department. Java:

public class Department {
    private long id;
    private String name;
    private User[] users;
    // omit getters/setters, constructors, toString methods
} Copy the code

JsonArrayToMemberArray. Java:

String departmentJson = "{'id' : 1, "
        + "'name': 'HR',"
        + "'users' : ["
            + "{'name': 'Alex','id': 1}, "
            + "{'name': 'Brian','id':2}, "
 + "{'name': 'Charles','id': 3}]}";  Gson gson = new Gson();  Department department = gson.fromJson(departmentJson, Department.class);  System.out.println(department); Copy the code

Running results:

Insert a picture description here

5.3.2 Member variables of type List

Deserialize a JSON array into a List member variable.

Department2.java:

public class Department2 {
 private long id;
 private String name;
 private List<User> users; 
   // omit getters/setters, constructors, toString methods
} Copy the code

Translation:

  String departmentJson = "{'id' : 1, "
          + "'name': 'HR',"
          + "'users' : ["
              + "{'name': 'Alex','id': 1}, "
              + "{'name': 'Brian','id':2}, "
 + "{'name': 'Charles','id': 3}]}";   Gson gson = new Gson();   Department2 department = gson.fromJson(departmentJson, Department2.class);   System.out.println(department); Copy the code

Running results:



6, JSON < — – > Set

6.1, the Set – > JSON

Serialize a HashSet toJson using the gson.tojson () method:

  Set<String> userSet = new HashSet<String>();
  userSet.add("Alex");
  userSet.add("Brian");
  userSet.add("Charles");
   
 Gson gson = new Gson();   String jsonString= gson.toJson(userSet);   System.out.println(jsonString); Copy the code

Running results:

Insert a picture description here


6.2, JSON – > Set

Serialize JSON to HashSet using the gson.fromjson () method and TypeToken:

  String jsonString = "['Alex','Brian','Charles','Alex']";
   
  Gson gson = new Gson(); 
   
  java.lang.reflect.Type setType = new TypeToken<HashSet<String>>(){}.getType();
  Set<String> userSet = gson.fromJson(jsonString, setType);   System.out.println(userSet); Copy the code

Running results:


7, Null value processing

The default behavior implemented in Gson is to ignore empty object fields.

For example, if email is not specified in the Employee object (that is, email is null), the email will not be serialized JSON output. Gson ignores null fields because this behavior allows for a more compact JSON output format.


7.1. How do I allow null values in serialization

To configure the Gson instance to output NULL, we must use the serializeNulls () of the GsonBuilder object.

Gson gson = new GsonBuilder()
        .serializeNulls()
        .create();
Copy the code


Version support

As the application changes over time, so do the model classes. Sometimes updating/deleting fields may be interrupted.

All of these changes can be marked with the @since annotation to keep track of model classes without breaking the interaction with other systems’ applications while these systems are exchanging deserialized JSON data.

8.1 @since Annotations

In Gson, you can maintain multiple versions of the same object using the @since annotation. You can use this annotation in classes, fields, and future methods. It takes a single parameter, ignoreVersionsAfter.

When we configure the version number “M.N” for the Gson instance, all class fields marked with a version greater than M.N are ignored. For example, if we configure Gson to version number “1.2”, then all fields with higher version numbers (e.g. 1.3, 1.4…) Will be ignored.

@Since(1.2)
private String email;
Copy the code

8.2. How do I write versioned classes using the @since annotation

Under the Employee class, we versioned three fields, firstName, lastName, and Email.

public class Employee 
{
    private Integer id;
 
    @Since(1.0)
 private String firstName;   @Since(1.1)  private String lastName;   @Since(1.2)  private String email; } Copy the code

8.3. Create a Gson instance with version support

To create a Gson instance with the @since annotation, use the gsonBuilder.setVersion () method:

Gson gson = new GsonBuilder()
            .setVersion(1.1)
            .create();
Copy the code

8.4, the instance,

8.4.1 Serialization with version support

Serialize the Employee object above the serial number.

Employee employeeObj = new Employee(1."Lokesh"."Gupta"."[email protected]");
 
Gson gson = new GsonBuilder()
        .setVersion(1.1)
        .setPrettyPrinting()
 .create();  System.out.println(gson.toJson(employeeObj)); Copy the code

Output:

{
  "id": 1.  "firstName": "Lokesh".  "lastName": "Gupta"
}
Copy the code


8.4.2 Deserialization with version support

We deserialize the JSON string into an object with version number Employee.

String json = "{'id': 1001, "
                + "'firstName': 'Lokesh',"
                + "'lastName': 'Gupta',"
                + "'email': '[email protected]'}";
 
Gson gson = new GsonBuilder()  .setVersion(1.1)  .setPrettyPrinting()  .create();  Employee employeeObj = gson.fromJson(json, Employee.class);  System.out.println(employeeObj); Copy the code

Output:

Employee [id=1001, firstName=Lokesh, lastName=Gupta, email=null]
Copy the code


9. Change the field name mapping between Java objects and JSON

In this gson@serializedName example, you can demonstrate changing field names between JSON and Java objects during serialization and deserialization.

9.1, @ SerializedName

By default, we assume that the Java model class and JSON will have exactly the same field name.

But sometimes this is not the case, and certain names are different. Now we must map someName from JSON to someOtherName from the Java class. This is where the @serializedName annotation comes in.

The @serializedName annotation indicates that the annotated member variable should serialize to JSON using the supplied name value as its field name. This annotation will override any FieldNamingPolicy that may have been using the GsonBuilder class, including the default FieldNamingPolicy.

Note that the value specified in this annotation must be a valid JSON field name.

Annotations contain attributes

  • Value – The name of the field required for serialization or deserialization.
  • Alternate – Alternate name of a field for deserialization. In addition to the value attribute, it provides more possible names. If more than one field matches an attribute, Gson will use the last one processed.


9.2. Change field names during serialization

Let’s take the Employee class with only four fields. We will create a JSON where “email” is written as the field name “emailId” :

public class Employee 
{
    private Integer id;
    private String firstName;
    private String lastName;
  @SerializedName(value = "emailId", alternate = "emailAddress")  private String email; } Copy the code

Let’s serialize an Employee instance and look at the JSON output:

Employee emp = new Employee(1001."Lokesh"."Gupta"."[email protected]");
 
Gson gson = new GsonBuilder().setPrettyPrinting().create();  
 
System.out.println(gson.toJson(emp));
Copy the code

Output:

{
  "id": 1001.  "firstName": "Lokesh".  "lastName": "Gupta".  "emailId": "[email protected]"
} Copy the code

9.3. Change the field name when deserializing

Map different field names during JSON deserialization into Java classes:

Json:

{
  "id": 1001.  "firstName": "Lokesh".  "lastName": "Gupta".  "email": "[email protected]". "emailAddress": "[email protected]" } Copy the code

The Main. Java:

String json = "{'id': 1001,"
        + "'firstName': 'Lokesh',"
        + "'lastName': 'Gupta',"
        + "'email': '[email protected]',"
        + "'emailAddress': '[email protected]'}";
 Gson gson = new GsonBuilder().setPrettyPrinting().create();  Employee emp = gson.fromJson(json, Employee.class);  System.out.println(emp); Copy the code

Output:

Employee [id=1001, firstName=Lokesh, lastName=Gupta, email=admin@gmail.com]
Copy the code


10. Exclude or ignore fields

Gson allows us to exclude or ignore fields from Java classes that we do not want to be included in serialization and deserialization.

Gson supports a number of built-in mechanisms for excluding top-level classes, fields, and field types.

10.1, @expose

GSON @ Expose annotations (. Com. Google GSON. Annotations. Expose) can be used to mark the object serialization or deserialization whether to Expose the fields (including live not included).

The @expose annotation is useful in the way you program to explicitly specify all fields that should be serialized or deserialized.

10.1.1. How to use @expose

@expose is optional and provides two configuration parameters:

  • Serialize – If true, a field with this annotation will be written in JSON during serialization.
  • Deserialize – If true, deserialize a field with this annotation from JSON.
@Expose(serialize = false) 
private String lastName;
 
@Expose (serialize = false, deserialize = false) 
private String emailAddress;
Copy the code

10.1.2 creating a Gson instance

If we create a Gson using New Gson() and execute the toJson() and fromJson() methods, @expose will have no effect on serialization and deserialization. To use this notation, we must use GsonBuilder classes and their excludeFieldsWithoutExposeAnnotation () method to create a Gson instance.

Gson gson = new GsonBuilder()
        .excludeFieldsWithoutExposeAnnotation()
        .create();
Copy the code

10.2. Exclude fields with modifiers

10.2.1. Transient field

By default, Gson excludes fields from serialization and deserialization if we mark them only as transient.

Remember that it does not prevent one-way conversions. It prevents both.

Transient has the same effect as @expose (serialize = false, deserialize = false).

@Expose(serialize = false) 
private String lastName;
 
private transient String emailAddress;
Copy the code

10.2.2 Other modifiers

Through the use of GsonBuilder excludeFieldsWithModifiers () method, we can rule out field with certain public modifier.

For example, if we want to exclude all static members of a class, we can create a Gson object like this:

Gson gson = new GsonBuilder()
        .excludeFieldsWithModifiers(Modifier.STATIC)
        .create();
Copy the code

We can use any number of Modifier constant to “excludeFieldsWithModifiers” method. Such as:

Gson gson = new GsonBuilder()
        .excludeFieldsWithModifiers(Modifier.STATIC, 
                            Modifier.TRANSIENT, 
                            Modifier.VOLATILE)
        .create();
Copy the code


10.3. Exclusion Strategy

If none of the above techniques work for us, then we can create our own strategy.

ExclusionStrategy is used to determine whether a field or top-level class should be serialized or deserialized as part of the JSON output/input.

  • For serialization, if the shouldSkipClass (Class) or shouldSkipField (fieldAttributes) method returns true, then the Class or field type is not part of the JSON output.
  • For deserialization, if the shouldSkipClass (Class) or shouldSkipField (fieldAttributes) method returns true, it is not set as part of the Java object structure.

For example, under the ExclusionStrategy definition, all fields annotated with the @hidden annotation are excluded:

//public @interface Hidden {
    // some implementation here
/ /}
 
// Excludes any field (or class) that is tagged with an "@Hidden"
public class HiddenAnnotationExclusionStrategy implements ExclusionStrategy {  public boolean shouldSkipClass(Class
               clazz) {  returnclazz.getAnnotation(Hidden.class) ! =null;  }   public boolean shouldSkipField(FieldAttributes f) {  returnf.getAnnotation(Hidden.class) ! =null;  } } Copy the code

To use this exclusion policy, set it in the GsonBuilder object:

GsonBuilder builder = new GsonBuilder();
builder.setExclusionStrategies( new HiddenAnnotationExclusionStrategy() );
 
Gson gson = builder.create();
Copy the code


Four, GsonBuilder

For simple use cases, use ‘Gson Gson = new Gson(); ‘Standard configuration is sufficient. However, if you want to customize the behavior of Gson, you can create new instances of Gson using the GsonBuilder custom configuration.

The GsonBuilder class provides a.create() method that returns a Gson instance.

Gson gson = new GsonBuilder().create(); 
Copy the code


1, GsonBuilder. SetPrettyPrinting () – beautifully printed JSON

By default, Gson creates a compact JSON string. This is very useful for reducing the amount of data transferred over the network.

However, this compact JSON is unfriendly to developers when developing/debugging applications. Format JSON output with nice print:

Gson gson = new GsonBuilder()
        .setPrettyPrinting()
        .create(); 
Copy the code


2, FieldNamingPolicy

The FieldNamingPolicy enumeration provides several standard naming conventions for JSON field names during serialization.

It helps the Gson instance correctly convert the Java field names to the desired JSON field names.

Note: None of the following naming conventions will affect fields annotated with @serializedName. We will validate the name generated for each policy that uses the User class.

User. Java:

public class User 
{
    private int id;
    private String first_Name;
    private String lastName;
 private String _email; } Copy the code

How to use FieldNamingPolicy:

User user = new User(1."Lokesh"."Gupta"."[email protected]");
         
Gson gson = new GsonBuilder()
                .setFieldNamingPolicy(FieldNamingPolicy.IDENTITY)
                .setPrettyPrinting().create(); 
 System.out.println(gson.toJson(user)); Copy the code

The following shows the different names that are converted under each naming strategy.


2.1, FieldNamingPolicy. IDENTITY

Using this naming policy, the field name does not change. This is the default policy:

{
  "id": 1.  "first_Name": "Lokesh".  "lastName": "Gupta".  "_email": "[email protected]"
} Copy the code


2.2, FieldNamingPolicy LOWER_CASE_WITH_DASHES

Gson changes Java field names from their camel case form to lowercase field names, where each word is separated by dashes (-).

{
  "id": 1.  "first_-name": "Lokesh".  "last-name": "Gupta".  "_email": "[email protected]"
} Copy the code


2.3, FieldNamingPolicy LOWER_CASE_WITH_DOTS

Gson will change the Java field names from their camel case form to lowercase field names with the dot (.) for each word. Space:

{
  "id": 1.  "first_.name": "Lokesh".  "last.name": "Gupta".  "_email": "[email protected]"
} Copy the code


2.4, FieldNamingPolicy LOWER_CASE_WITH_UNDERSCORES

Gson changes the Java field names from their camel case form to lowercase field names, where each word is separated by an underscore (_).

{
  "id": 1.  "first__name": "Lokesh".  "last_name": "Gupta".  "_email": "[email protected]"
} Copy the code


2.5、 FieldNamingPolicy.UPPER_CAMEL_CASE

Gson will ensure that the first “letter” of the Java field name serialized to JSON format is capitalized:

{
  "Id": 1.  "First_Name": "Lokesh".  "LastName": "Gupta".  "_Email": "[email protected]"
} Copy the code


2.6, FieldNamingPolicy UPPER_CAMEL_CASE_WITH_SPACES

Gson will ensure that the first “letter” of the Java field name is capitalized when it is serialized to JSON format, and that the words are separated by Spaces:

{
  "Id": 1.  "First_ Name": "Lokesh".  "Last Name": "Gupta".  "_Email": "[email protected]"
} Copy the code


3, GsonBuilder. SerializeNulls serialize () – a null value

By default, Gson ignores null values during serialization. However, sometimes we want to serialize a field with a null value so that it must appear in JSON. To do this, use the serializeNulls() method:

Employee employeeObj = new Employee(1."Lokesh"."Gupta".null);
                 
Gson gson = new GsonBuilder()
        .serializeNulls()
        .setPrettyPrinting().create(); 
 System.out.println(gson.toJson(employeeObj)); Copy the code

Output:

{
  "id": 1.  "firstName": "Lokesh".  "lastName": "Gupta".  "emailId": null
} Copy the code


4, GsonBuilder. SetExclusionStrategies ()

ExclusionStrategy is used to determine whether a field or top-level class should be serialized or deserialized as part of the JSON output/input.

  • For serialization, if the shouldSkipClass (Class) method returns true, the Class or field type will not be printed in JSON.
  • For deserialization, if shouldSkipClass (Class) returns true, it is not set as part of the Java object structure.

The shouldSkipField (attribute) method is the same rule.

In the example below, member fields that use the @nPI annotation and belong to instances of the Account class are not serialized and deserialized.

Gson gson = new GsonBuilder()
    .setExclusionStrategies(new ExclusionStrategy() {
        @Override
        public boolean shouldSkipField(FieldAttributes f) {
            returnf.getAnnotation(NPI.class) ! =null;
 }   @Override  public boolean shouldSkipClass(Class
                clazz) {  returnclazz.getAnnotation(Account.class) ! =null;  }  })  .setPrettyPrinting()  .create(); Copy the code


5. Gsonbuilder.setlenient () — Loose JSON syntax rules

During deserialization, Gson uses a loose JsonReader class. This means that it only accepts compatible JSON input.

If JSON violates one of the structure rules, it throws a MalformedJsonException. If we set Lenient to true, it will ignore some violations and try to read misformed JSON.

Gson gson = new GsonBuilder()
        .setLenient()
        .setPrettyPrinting().create(); 
Copy the code


Five, the JsonReader

Use the Gson JsonReader class, which is a pull-based stream JSON parser. It helps to read JSON as a token stream.

1, the JsonReader

  • JsonReader is a streaming JSON parser and an example of a Pull Parser. Pull Parser parses the JSON token and pushes it to the event handler.
  • It helps to read JSON (RFC 7159) encoded values as token streams.
  • It reads literals (string, number, Boolean, and NULL) as well as the start and end delimiters for objects and arrays.
  • The tokens are traversed in depth-first order, the same order that appears in the JSON document.

2, Tokens

In stream mode, each JSON data is treated as a separate token.

When we process them using JsonReader, each token is processed sequentially. For example,

{
    "name":"Lokesh"
}
Copy the code

When parsed using JsonReader, the above JSON generates four tokens:

  • Token 1 = {
  • Token 2 = name
    • Token 3 = Lokesh
  • Token 4 = }

Create GSON JsonReader

We can use its simple constructor to create an instance of JsonReader that takes an input stream of type java.io.Reader.

String json = "{}";
JsonReader jsonReader = new JsonReader( new StringReader(json) );
Copy the code

Depending on the source of the JSON stream, we can use one of the following readers:

  • BufferedReader
  • LineNumberReader
  • CharArrayReader
  • InputStreamReader
  • FileReader
  • FilterReader
  • PushbackReader
  • PipedReader
  • StringReader


Read the JSON stream

After creating a JsonReader that contains a valid JSON source, we can begin to iterate through the stream token and view the token value.

Here is an example of reading simple JSON in token form using JsonReader:

import java.io.IOException;
import java.io.StringReader;
 
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
 public class Main {  public static void main(String[] args) throws Exception  {   String json = "{'id': 1001,'firstName': 'Lokesh','lastName': 'Gupta','email': null}";   JsonReader jsonReader = new JsonReader(new StringReader(json));  jsonReader.setLenient(true);   try  {  while (jsonReader.hasNext())  {  JsonToken nextToken = jsonReader.peek();   if (JsonToken.BEGIN_OBJECT.equals(nextToken)) {   jsonReader.beginObject();   } else if (JsonToken.NAME.equals(nextToken)) {   String name = jsonReader.nextName();  System.out.println("Token KEY >>>> " + name);   } else if (JsonToken.STRING.equals(nextToken)) {   String value = jsonReader.nextString();  System.out.println("Token Value >>>> " + value);   } else if (JsonToken.NUMBER.equals(nextToken)) {   long value = jsonReader.nextLong();  System.out.println("Token Value >>>> " + value);   } else if (JsonToken.NULL.equals(nextToken)) {   jsonReader.nextNull();  System.out.println("Token Value >>>> null");   } else if (JsonToken.END_OBJECT.equals(nextToken)) {   jsonReader.endObject();   }  }  } catch (IOException e) {  e.printStackTrace();  } finally {  jsonReader.close();  }  } } Copy the code

Output:

Token KEY >>>> id
Token Value >>>> 1001
 
Token KEY >>>> firstName
Token Value >>>> Lokesh
 Token KEY >>>> lastName Token Value >>>> Gupta  Token KEY >>>> email Token Value >>>> null Copy the code

In the example above:

  • Returns true if JsonReader’s hasNext () method has more tokens.
  • The peek () method returns the next JSON token, but does not move to it.
  • Subsequent calls to peek () will return the same JSON token.
  • You can use the constants of the JsonToken class to check the type of token returned.
  • Use the beginArray () and endArray () methods to check the left and right parentheses “[” and”] “of the array. Use the beginObject () and endObject () methods to check the opening and closing brackets “{” and”} “of the object.
  • The key of the token is of type jsontoken.name. Get the key name using the nextName () method.
  • Once the token type is determined, get the value of the token using methods such as nextLong (), nextString (), nextInt (), and so on. Empty literals can be used with nextNull () or skipValue ().
  • All the next… The () methods all return the value of the current tag and move the internal pointer to the next.
  • A strict parser should fail with an exception when encountering an unknown name. A generous parser should call skipValue () to recursively skip the nested token for that value, or conflicts may occur.


Six, JsonParser

Gson JsonParser is used to parse Json data into a parse tree of JsonElements, and hence into JsonObjects.

JsonObject can be used to access values using the corresponding key in the JSON string.

Create JsonParser

The JsonParser class has only one default constructor and requires no parameters or configuration.

JsonParser parser = new JsonParser();
Copy the code


2. Convert JSON

The JsonParser class provides three methods to supply JSON as a source and parse it into a JsonElements tree.

  • JsonElement Parse (JsonReader JSON) – Uses JsonReader to read JSON as a token stream and return the next value from the JSON stream as an analysis tree.
  • JsonElement Parse (java.io.Reader JSON) – Reads JSON using the specified Reader and parses the JSON string into a parse tree.
  • JsonElement Parse (java.lang.String json) – Parses the specified JSON String into a parse tree.

All three methods will throw JsonParseException and JsonSyntaxException if the specified text is not valid JSON.


JsonElement, JsonObject, and JsonArray

Once the JSON string is parsed in the JsonElement tree, we can use its various methods to access JSON data elements.

For example, use a type-checking method to find out what type of JSON element it represents:

jsonElement.isJsonObject();
jsonElement.isJsonArray();
jsonElement.isJsonNull();
jsonElement.isJsonPrimitive();
Copy the code

We can convert JsonElement to JsonObject and JsonArray using the corresponding methods:

JsonObject jsonObject = jsonElement.getAsJsonObject();
JsonArray jsonArray = jsonElement.getAsJsonArray();
Copy the code

Once you have a JsonObject or JsonArray instance, you can use its get () method to extract fields from it.


4. Gson JsonParser example

Parse JSON to JsonElement (and JsonObject) using JsonParser and get JSON values using keys:

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
 
public class Main {  public static void main(String[] args) throws Exception  {  String json = "{'id': 1001, "  + "'firstName': 'Lokesh',"  + "'lastName': 'Gupta',"  + "'email': '[email protected]'}";   JsonElement jsonElement = new JsonParser().parse(json);   JsonObject jsonObject = jsonElement.getAsJsonObject();   System.out.println( jsonObject.get("id")); System.out.println( jsonObject.get("firstName")); System.out.println( jsonObject.get("lastName")); System.out.println( jsonObject.get("email")); } } Copy the code

Output:

1001
"Lokesh"
"Gupta"
"[email protected]"
Copy the code

Get the JsonObject from fromJson()

We can use the Gson instance with its fromJson () method to get the same result:

String json = "{'id': 1001, "
        + "'firstName': 'Lokesh',"
        + "'lastName': 'Gupta',"
        + "'email': '[email protected]'}";
 
JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class);  System.out.println(jsonObject.get("id")); System.out.println(jsonObject.get("firstName")); System.out.println(jsonObject.get("lastName")); System.out.println(jsonObject.get("email")); Copy the code

Output:

String json = "{'id': 1001, "
        + "'firstName': 'Lokesh',"
        + "'lastName': 'Gupta',"
        + "'email': '[email protected]'}";
 
JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class);  System.out.println(jsonObject.get("id")); System.out.println(jsonObject.get("firstName")); System.out.println(jsonObject.get("lastName")); System.out.println(jsonObject.get("email")); Copy the code


Iterate over the JSON tree structure

Here is a complete example of how to iterate over a JsonElement obtained from a JsonReader:

JsonParser parser = new JsonParser();

String json = "{ \"f1\":\"Hello\",\"f2\":{\"f3:\":\"World\"}}";

JsonElement jsonTree = parser.parse(json);
 if(jsonTree.isJsonObject()){  JsonObject jsonObject = jsonTree.getAsJsonObject();   JsonElement f1 = jsonObject.get("f1");   JsonElement f2 = jsonObject.get("f2");   if(f2.isJsonObject()){  JsonObject f2Obj = f2.getAsJsonObject();   JsonElement f3 = f2Obj.get("f3");  }  } Copy the code


Custom serialization and deserialization

Gson provides excellent functionality for default serialization and deserialization.

However, we may encounter situations where the default and built-in customization options do not solve our problem. In this case, we can use custom serialization and deserialization through the two interfaces JsonSerializer and JsonDeserializer.

1. Custom serialization

1.1. JsonSerializer interface

JsonSerializer. Java:

public interface JsonSerializer<T> 
{
    public JsonElement serialize(T value, Type type,
 JsonSerializationContext jsonSerializationContext) {
    }
} Copy the code

Create custom for Json serializer, we also need to through GsonBuilder. RegisterTypeAdapter (Type, Object) to register the serializer.

When Gson encounters a field of the specified type, it calls its callback method serialize () during serialization.


1.2. Custom serialization examples

Suppose we had a situation where we had to serialize a Java object to JSON so that all Boolean values should be written as 1 or 0 instead of printing true or false.

Let’s write a custom serializer for this requirement.

BooleanSerializer. Java:

import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
 
public class BooleanSerializer implements JsonSerializer<Boolean> {   public JsonElement serialize(Boolean aBoolean, Type type,  JsonSerializationContext jsonSerializationContext)  {  if(aBoolean){  return new JsonPrimitive(1);  }  return new JsonPrimitive(0);  } } Copy the code

Let’s write a program that registers an instance of JsonSerializer using registerTypeAdapter () and uses it to serialize a Java object to JSON.

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
 
public class Main 
{
 public static void main(String[] args) throws Exception  {  Employee emp = new Employee(1."Lokesh"."Gupta"."[email protected]".true);   Gson gson = new GsonBuilder()  .registerTypeAdapter(Boolean.class, new BooleanSerializer())  .setPrettyPrinting()  .create();   String json = gson.toJson(emp);   System.out.println(json);  } } Copy the code

Note that the program output serializes the value of the key “active” to 1:

{
  "id": 1.  "firstName": "Lokesh".  "lastName": "Gupta".  "email": "[email protected]". "active": 1 } Copy the code


2. Custom deserialization

2.1. JsonDeserializer interface

Custom deserializers must implement the JsonDeserializer interface. The JsonDeserializer ports are as follows:

JsonDeserializer. Java:

public interface JsonDeserializer<T> 
{    
    public Boolean deserialize(JsonElement jsonElement, 
 Type type, JsonDeserializationContext jsonDeserializationContext) 
 throws JsonParseException;
} Copy the code

As Json to create custom after the deserializer, we also need to through GsonBuilder. RegisterTypeAdapter (Type, Object) to register the deserializer.

When Gson encounters a field of the specified type, it calls its callback method deserialize () during serialization.

2.2. Custom deserialization examples

Suppose some service returns the date field to us as day, month, year, and so on. They might make sense in a JSON string, but in Java they only make sense as part of a single java.time.LocalDate object.

The employee. Json:

{
  "id": 1.  "firstName": "Lokesh".  "lastName": "Gupta".  "email": "[email protected]". "day": 11. "month": 8. "year": 2019 } Copy the code

We’ll customize deserialization and combine the last three fields into a LocalDate object.

Our Employee looks something like this. This includes the necessary getters and setters and constructors.

The Employee. Java:

public class Employee 
{
    private Integer id;
    private String firstName;
    private String lastName;
 private String email;  private LocalDate dob; } Copy the code

The custom deserializer class looks like this:

EmployeeDeserializer. Java:

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
 public class EmployeeDeserializer implements JsonDeserializer<Employee> {  @Override  public Employee deserialize(JsonElement json, Type typeOfT,  JsonDeserializationContext context) throws JsonParseException  {  JsonObject jsonObject = json.getAsJsonObject();   LocalDate localDate = LocalDate.of(  jsonObject.get("year").getAsInt(),  jsonObject.get("month").getAsInt(),  jsonObject.get("day").getAsInt()  );   return new Employee(  jsonObject.get("id").getAsInt(),  jsonObject.get("firstName").getAsString(),  jsonObject.get("lastName").getAsString(),  jsonObject.get("email").getAsString(),  localDate);  } } Copy the code

Register the deserializer and parse the given JSON into a Java object:

The Main. Java:

public class Main 
{
    public static void main(String[] args) throws Exception 
    {
        String json = "{'id': 1001,"
 + "'firstName': 'Lokesh',"  + "'lastName': 'Gupta',"  + "'email': '[email protected]', "  + "'day': 11, "  + "'month': 8, "  + "'year': 2019}";   Gson gson = new GsonBuilder()  .registerTypeAdapter(Employee.class, new EmployeeDeserializer())  .create();   Employee employee = gson.fromJson(json, Employee.class);   System.out.println(employee);  } } Copy the code

Note that the program output combines three separate fields into a single LocalDate object:

Employee [id=1001.        firstName=Lokesh, 
        lastName=Gupta, 
        email=howtodoinjava@gmail.com, 
        dob=2019-08-11]
Copy the code

Reference: [1] : Gson [2] : Gson — Introduction [3] : Gson — Installation [4] : Gson-gson [5] : GSON — Serialize and Deserialize JSON [6] : GSON — Pretty Printing for JSON Output [7] : GSON — Parse JSON array to Java Array or list [8] : GSON — Serialize and deserialize JSON to Set [9] : Gson — GsonBuilder Configuration Examples [10] : Gson @since — Version Support [11] : Gson @serializedName [12] : Gson — JsonReader [13] : Gson — JsonReader [14] : Gson — JsonParser [15] : Gson-jsonParser

This article is formatted using MDNICE