GSON tutorials with code examples

Introduction

This post explains how to use GSON library in java.In my previous post I explained the process deserialization. Now lets see how to use google’s GSON library.Its one of the most popular libraries to manipulate JSON to java and vice versa.Gson uses┬áreflection, so it does not require classes being serialized or de-serialized to be modified

GSON dependency:

Add below dependency in the application’s pom.xml . At the time of this post 2.8.6 was the latest version.Find the latest version here.

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.6</version>
  </dependency>

Code examples:

Json to Pojo :

In the below example, I am reading json as a string. And then using gson.fromJson method , I am converting it to a java object.

package com.codingbrains.gson;

import com.google.gson.Gson;
import java.nio.file.Files;
import java.nio.file.Paths;
import lombok.SneakyThrows;

/**
 * Reads JSON from file and parses it to a POJO
 */
public class jsonToPojo {

//SneakyThrows annotation will internally declare all checked exceptions.
  @SneakyThrows
  public static void main(String[] args) {
    //Read a Json from file and convert it to a string
    String strJson = new String(Files.readAllBytes(Paths.get("src/main/resources/json/Person.json")));
    //Create new GSON object
    Gson gson = new Gson();

    //Parse the JSON string to Person object
    Person person = gson.fromJson(strJson, Person.class);

    //Print required information from POJO
    System.out.println("Person Name is " + person.getName());
  }
}

Output:

Person Name is Dhoni

POJO to Json:

I have an object called Person . Using gson.toJson method , we can convert the POJO to a json.

package com.codingbrains.gson;

import com.google.gson.Gson;
import java.util.Arrays;
import java.util.List;

/**
 * Creates an object and then converts it to a JSON.
 * Uses GSON library
 */
public class PojoToJson {

  public static void main(String[] args) {
    //Create a Person object
    Person person = initializePerson();
    //Create a GSON object
    Gson gson = new Gson();
    //Convert Object to JSON string
    String strVirat = gson.toJson(person);
    //Print the result
    System.out.println(strVirat);

  }

  private static Person initializePerson() {
    Person virat = new Person();
    virat.setName("Virat Kohli");
    virat.setAge("30");
    virat.setPlace("Bangalore");
    virat.setTitle("Mr");
    List<String> hobbies = Arrays.asList("cricket", "Running", "travelling", "Sledging");
    virat.setMyHobbies(hobbies);
    return virat;

  }
}

Output:

{"name":"Virat Kohli","age":"30","place":"Bangalore","title":"Mr","myHobbies":["cricket","Running","travelling","Sledging"]}

How to Pretty print a json?

Whenever we print a json using gson library , it looks pretty ugly. To make it pretty we can enable setPrettyPrinting() on the gson object.

package com.codingbrains.gson;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import lombok.SneakyThrows;

public class PrettyPrintExample {
  //SneakyThrows annotation will internally declare all checked exceptions.
  @SneakyThrows
  public static void main(String[] args) {
    List<String> cars= Arrays.asList("Fiat","BMW","Lamborghini");
    //Create new GSON object
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String prettyJson=gson.toJson(cars);
    System.out.println("pretty "+prettyJson);
  }
}

Output:

The output json looks pretty.

pretty [
"Fiat",
"BMW",
"Lamborghini"
]

Download this code:

You can download the code examples mentioned in this post from here.

You may also like...

Leave a Reply

Your email address will not be published.