GSON In Java

GSON In Java

GSON In Java

Gradle

// Module

compile "com.google.code.gson:gson:$gsonLibVersion"

// Project 

   gsonLibVersion = "2.8.2"

GSON

  • GSON is Google’s JSON parser and generator for Java.

Gson Instance

  1. You can use GSON you must first create a new Gson object. There are two ways to create a Gson instance:
    1. new Gson()
    2. new GsonBuilder().create()

Transient variable

  • If you make a field in a Java class transient then GSON will ignore it in both serialization and deserialization.

For example:

public transient String password = null;

Annotation

  • @Expose Annotation
  • @Expose annotation (com.google.gson.annotations.Expose) can be used to mark a field to be exposed or not (included or not) when an object is serialized or deserialized. The @Expose annotation can take two parameters. Each parameter is a boolean which can take either the value true or false.
  • @Expose(serialize = true);
  • @Expose(serialize = false);
  • @Expose(deserialize = true);
  • @Expose(deserialize = false);
  • @Expose(serialize = true , deserialize = false);
  • @Expose(serialize = false, deserialize = true);

Pretty Printing

  • GSON offers a pretty printing option where the JSON is printed so it is more readable in a text editor.

Gson gson = new GsonBuilder().setPrettyPrinting().create();

For example:

{
  "brand": "Rover",
  "doors": 5
}
  • By default the Gson instance created with new Gson() prints (generates) as compact as possible JSON.

For example:

{"brand":"Rover","doors":5}

Gson streaming API

  • Gson streaming API is a low-level API that reads and writes JSON as discrete tokens (JsonTokens). The main classes are JsonReader and JsonWriter. JsonToken is a structure, name or value type in a JSON-encoded string.

These are the JsonToken types:

  1. BEGIN_ARRAY : opening of a JSON array {
  2. END_ARRAY :  closing of a JSON array }
  3. BEGIN_OBJECT : opening of JSON object [
  4. END_OBJECT :  closing of JSON object ]
  5. NAME :  a JSON property name
  6. STRING : a JSON string
  7. NUMBER : a JSON number (double, long, or int)
  8. BOOLEAN : a JSON boolean value
  9. NULL : a JSON null
  10. END_DOCUMENT : end of the JSON stream.

Gson API

Gson has three types of API:

  • Data binding API

Data binding API converts JSON to and from POJO using property accessors. Gson processes JSON data using data type adapters. It is similar to XML JAXB parser.

  • Tree model API

Tree model API creates an in-memory tree representation of the JSON document. It builds a tree of JsonElements. It is similar to XML DOM parser.

  • Streaming API

Streaming API is a low-level API that reads and writes JSON content as discrete tokens with JsonReader and JsonWriter. These classes read data as JsonTokens. This API has the lowest overhead and is fast in read/write operations. It is similar to Stax parser for XML.

toJson()

  • The toJson() method serializes the specified object into its equivalent JSON representation.
package com.codemother.gson;

import com.google.gson.Gson;
import java.util.HashMap;
import java.util.Map;

public class GsonToJson {

    public static void main(String[] args) {
        Map<Integer, String> colours = new HashMap<>();
        colours.put(1, "blue");
        colours.put(2, "yellow");
        colours.put(3, "green");
        
        System.out.println(new Gson().toJson(colours));
    }
}
Run:
{"1":"blue","2":"yellow","3":"green"}

fromJson()

  • fromJson() method deserializes the specified JSON into an object of the specified class.
package com.codemother.model;
import com.google.gson.Gson;
class Item
{
    private String name;
    private int quantity;

    @Override
    public String toString()
    {
        return "Item{" + "name=" + name + ", quantity=" + quantity + '}';
    }
}

class GsonFromJson
{
    public static void main(String[] args)
    {
        String json_string = "{\"name\":\"chair\",\"quantity\":3}";

        Item item = new Gson().fromJson(json_string, Item.class);

        System.out.println(item);
    }
}

FieldNamingPolicy UpperCase

package com.codemother.gson;

import com.google.gson.FieldNamingPolicy;
import com.google.gson.GsonBuilder;
import java.io.IOException;
import java.io.PrintWriter;

class Item
{
    private String name;
    private int quantity;

    public Item(String name, int quantity)
    {
        this.name = name;
        this.quantity = quantity;
    }
}

public class GsonBuilderUpperCase
{
    public static void main(String[] args) throws IOException
    {

        try (PrintWriter writer = new PrintWriter(System.out))
        {
            Item item1 = new Item("chair", 3);
            new GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create().toJson(item1, writer);
        }
    }
}




Run:
{"Name":"chair","Quantity":3}

GsonPrettyPrinting

package com.codemother.gson;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.HashMap;
import java.util.Map;

public class GsonPrettyPrinting
{
    public static void main(String[] args)
    {
        Gson gson = new GsonBuilder() .setPrettyPrinting() .create();

        Map<String, Integer> items = new HashMap<>();

        items.put("chair", 3);
        items.put("pencil", 1);
        items.put("book", 5);

        gson.toJson(items, System.out);
    }
}



Run
{
  "chair": 3,
  "book": 5,
  "pencil": 1
}

GsonExcludeFields

package com.codemother.gson;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.Expose;

enum MaritalStatus
{
    SINGLE,
    MARRIED,
    DIVORCED,
    UNKNOWN
}

class Person
{
    @Expose
    private String firstName;
    @Expose
    private String lastName;
    
    private MaritalStatus maritalStatus;

    public Person(String firstName, String lastName, MaritalStatus maritalStatus)
    {

        this.firstName = firstName;
        this.lastName = lastName;
        this.maritalStatus = maritalStatus;
    }

    public Person()
    {
    }
}

public class GsonExcludeFields
{
    public static void main(String[] args)
    {
        Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting().create();
        Person p = new Person("Jack", "Sparrow", MaritalStatus.UNKNOWN);
        gson.toJson(p, System.out);
    }
}


Run
{
  "firstName": "Jack",
  "lastName": "Sparrow"
}

TypeToken

List<Car> cars = gson.fromJson(reader, 
                    new TypeToken<List<Car>>(){}.getType());

The flutter tutorial  is a website that bring you the latest and amazing resources of code. All the languages codes are included in this website. The languages like flutter, android, java,kotlin etc.with the help of this languages any user can develop the beautiful application

For more information about Flutter. visit www.fluttertutorial.in