Convert JSON File to Java Object in Java using Gson

Tags: JSON gson Gson fromJson Gson TypeToken JSON file to HashMap JSON file to List JSON file to object FileReader

In this Java Gson tutorial we learn how to convert a JSON file into a Java object using the Gson class of the Gson library. By different Java example programs we show you how to convert a JSON file into a HashMap object, a list of Map, an object of custom defined classes or a List of objects.

How to add Gson to the Java project

To use the Gson library in the Gradle build project, add the following dependency into the build.gradle file.

implementation group: 'com.google.code.gson', name: 'gson', version: '2.8.7'

To use the Gson library in the Maven build project, add the following dependency into the pom.xml file.

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

Or you can download the Gson jar file from Maven Central at gson-2.8.7.jar

To have more information about the Gson library you can visit the project repository at github.com/google/gson

How to convert JSON File to HashMap

For example, we have a JSON file at D:\Data\sample1.json with the content as below.

D:\Data\sample1.json

{
  "firstName": "Simple",
  "lastName": "Solution",
  "email": "contact@simplesolution.dev",
  "website": "https://simplesolution.dev",
  "address": {
    "street": "Simple Street",
    "city": "City Name",
    "country": "Country Name"
  }
}

In the following Java example program, we show you how to read the JSON file above and convert it to a HashMap object using Java FileReader class and Gson.fromJson() method.

JsonFileToJavaObjectExample1.java

import com.google.gson.Gson;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.HashMap;

public class JsonFileToJavaObjectExample1 {
    public static void main(String... args) throws FileNotFoundException {
        FileReader fileReader = new FileReader("D:\\Data\\sample1.json");

        Gson gson = new Gson();
        HashMap<String, String> result = gson.fromJson(fileReader, HashMap.class);

        System.out.println("Converted HashMap object: ");
        System.out.println(result);
    }
}
The output is:
Converted HashMap object: 
{firstName=Simple, lastName=Solution, website=https://simplesolution.dev, address={street=Simple Street, city=City Name, country=Country Name}, email=contact@simplesolution.dev}

How to convert JSON File to List of Map

For example, we have a JSON file at D:\Data\sample2.json with the content to store a list of objects as below.

D:\Data\sample2.json

[
  {
    "firstName": "Simple",
    "lastName": "Solution",
    "email": "contact@simplesolution.dev",
    "website": "https://simplesolution.dev",
    "address": {
      "street": "Simple Street",
      "city": "City Name",
      "country": "Country Name"
    }
  },
  {
    "firstName": "Java",
    "lastName": "Tutorial",
    "email": "java@simplesolution.dev",
    "website": "https://simplesolution.dev",
    "address": {
      "street": "Test Street",
      "city": "City Name",
      "country": "Country Name"
    }
  },
  {
    "firstName": "Gson",
    "lastName": "Learn",
    "email": "gson@simplesolution.dev",
    "website": "https://simplesolution.dev/tag/gson",
    "address": {
      "street": "Gson Street",
      "city": "City Name",
      "country": "Country Name"
    }
  }
]

In the following Java example program, we show you how to read the JSON file above and convert it to a List of Map objects using Java FileReader class and Gson.fromJson() method.

JsonFileToJavaObjectExample2.java

import com.google.gson.Gson;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.List;
import java.util.Map;

public class JsonFileToJavaObjectExample2 {
    public static void main(String... args) throws FileNotFoundException {
        FileReader fileReader = new FileReader("D:\\Data\\sample2.json");

        Gson gson = new Gson();
        List<Map> list = gson.fromJson(fileReader, List.class);

        System.out.println("Converted List of HashMap: ");
        for (Map item : list) {
            System.out.println(item);
        }
    }
}
The output is:
Converted List of HashMap: 
{firstName=Simple, lastName=Solution, email=contact@simplesolution.dev, website=https://simplesolution.dev, address={street=Simple Street, city=City Name, country=Country Name}}
{firstName=Java, lastName=Tutorial, email=java@simplesolution.dev, website=https://simplesolution.dev, address={street=Test Street, city=City Name, country=Country Name}}
{firstName=Gson, lastName=Learn, email=gson@simplesolution.dev, website=https://simplesolution.dev/tag/gson, address={street=Gson Street, city=City Name, country=Country Name}}

How to convert JSON File to Java object

In the following Java example program, we show you how to convert the JSON file to an object of a custom defined class.

Firstly we define the Address and Customer class to represent the customer record as the below Java code.

Address.java

public class Address {
    private String street;
    private String city;
    private String country;

    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }
}

Customer.java

public class Customer {
    private String firstName;
    private String lastName;
    private String email;
    private String website;
    private Address address;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getWebsite() {
        return website;
    }

    public void setWebsite(String website) {
        this.website = website;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }
}

The Java program below converts D:\Data\sample1.json to a Customer object.

JsonFileToJavaObjectExample3.java

import com.google.gson.Gson;

import java.io.FileNotFoundException;
import java.io.FileReader;

public class JsonFileToJavaObjectExample3 {
    public static void main(String... args) throws FileNotFoundException {
        FileReader fileReader = new FileReader("D:\\Data\\sample1.json");

        Gson gson = new Gson();
        Customer customer = gson.fromJson(fileReader, Customer.class);

        System.out.println("First Name: " + customer.getFirstName());
        System.out.println("Last Name: " + customer.getLastName());
        System.out.println("Email: " + customer.getEmail());
        System.out.println("Website: " + customer.getWebsite());
        System.out.println("Street: " + customer.getAddress().getStreet());
        System.out.println("City: " + customer.getAddress().getCity());
        System.out.println("Country: " + customer.getAddress().getCountry());
    }
}
The output is:
First Name: Simple
Last Name: Solution
Email: contact@simplesolution.dev
Website: https://simplesolution.dev
Street: Simple Street
City: City Name
Country: Country Name

How to convert JSON File to List of objects

The Java program below converts D:\Data\sample2.json to a List of Customer objects.

JsonFileToJavaObjectExample4.java

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.lang.reflect.Type;
import java.util.List;

public class JsonFileToJavaObjectExample4 {
    public static void main(String... args) throws FileNotFoundException {
        FileReader fileReader = new FileReader("D:\\Data\\sample2.json");

        Gson gson = new Gson();
        Type type = new TypeToken<List<Customer>>(){}.getType();
        List<Customer> customers = gson.fromJson(fileReader, type);

        for(Customer customer : customers) {
            System.out.println("First Name: " + customer.getFirstName());
            System.out.println("Last Name: " + customer.getLastName());
            System.out.println("Email: " + customer.getEmail());
            System.out.println("Website: " + customer.getWebsite());
            System.out.println("Street: " + customer.getAddress().getStreet());
            System.out.println("City: " + customer.getAddress().getCity());
            System.out.println("Country: " + customer.getAddress().getCountry());
            System.out.println();
        }
    }
}
The output is:
First Name: Simple
Last Name: Solution
Email: contact@simplesolution.dev
Website: https://simplesolution.dev
Street: Simple Street
City: City Name
Country: Country Name

First Name: Java
Last Name: Tutorial
Email: java@simplesolution.dev
Website: https://simplesolution.dev
Street: Test Street
City: City Name
Country: Country Name

First Name: Gson
Last Name: Learn
Email: gson@simplesolution.dev
Website: https://simplesolution.dev/tag/gson
Street: Gson Street
City: City Name
Country: Country Name

Happy Coding 😊