Convert JSON String to Java Object in Java using Gson

Tags: JSON gson Gson fromJson Gson TypeToken Convert

In this Java Gson tutorial we learn how to use the Gson library to convert a JSON String into a Java object by using Gson class. Via different Java code examples we show you how to convert a JSON String into Java HashMap, an object of a custom defined class 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

Convert a JSON String to a HashMap

For example, we have a JSON String as below.

{
  "firstName": "Simple",
  "lastName": "Solution",
  "email": "contact@simplesolution.dev",
  "website": "https://simplesolution.dev"
}

In the following Java program, we show you how to use the Gson library to convert the JSON String to an object of HashMap.

JsonStringToJavaObjectExample1.java

import com.google.gson.Gson;

import java.util.HashMap;

public class JsonStringToJavaObjectExample1 {
    public static void main(String... args) {
        String jsonString = "{\n" +
                "  \"firstName\": \"Simple\",\n" +
                "  \"lastName\": \"Solution\",\n" +
                "  \"email\": \"contact@simplesolution.dev\",\n" +
                "  \"website\": \"https://simplesolution.dev\"\n" +
                "}";

        Gson gson = new Gson();
        HashMap<String, String> result = gson.fromJson(jsonString, 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, email=contact@simplesolution.dev}

Convert multi level JSON String to HashMap

For example, we have a multi level JSON String as below.

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

By using Gson.fromJson() method we can convert the multi level JSON to HashMap object as belowJava example program.

JsonStringToJavaObjectExample2.java

import com.google.gson.Gson;

import java.util.HashMap;

public class JsonStringToJavaObjectExample2 {
    public static void main(String... args) {
        String jsonString = "{\n" +
                "  \"firstName\": \"Simple\",\n" +
                "  \"lastName\": \"Solution\",\n" +
                "  \"email\": \"contact@simplesolution.dev\",\n" +
                "  \"website\": \"https://simplesolution.dev\",\n" +
                "  \"address\": {\n" +
                "    \"street\": \"Simple Street\",\n" +
                "    \"city\": \"City Name\",\n" +
                "    \"country\": \"Country Name\"\n" +
                "  }\n" +
                "}";

        Gson gson = new Gson();
        HashMap result = gson.fromJson(jsonString, 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}

Below is the debug screenshot that watches result variable to help you look closer to the output object.

Convert JSON String to Java Object in Java using Gson

Convert JSON String to an object of a custom defined class

For example we have the JSON string as below to represent a customer record.

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

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 shows you how to use the Gson.fromJson() method to convert the JSON string above to Customer object.

JsonStringToJavaObjectExample3.java

import com.google.gson.Gson;

public class JsonStringToJavaObjectExample3 {
    public static void main(String... args) {
        String jsonString = "{\n" +
                "  \"firstName\": \"Simple\",\n" +
                "  \"lastName\": \"Solution\",\n" +
                "  \"email\": \"contact@simplesolution.dev\",\n" +
                "  \"website\": \"https://simplesolution.dev\",\n" +
                "  \"address\": {\n" +
                "    \"street\": \"Simple Street\",\n" +
                "    \"city\": \"City Name\",\n" +
                "    \"country\": \"Country Name\"\n" +
                "  }\n" +
                "}";

        Gson gson = new Gson();
        Customer customer = gson.fromJson(jsonString, 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

Convert JSON String to List of objects

For example, we have a list of customers in JSON String as below.

[
  {
    "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"
    }
  }
]

The following Java example shows you how to convert the above JSON String into a List of Customer object in Java.

JsonStringToJavaObjectExample4.java

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

import java.lang.reflect.Type;
import java.util.List;

public class JsonStringToJavaObjectExample4 {
    public static void main(String... args) {
        String jsonString = "[\n" +
                "  {\n" +
                "    \"firstName\": \"Simple\",\n" +
                "    \"lastName\": \"Solution\",\n" +
                "    \"email\": \"contact@simplesolution.dev\",\n" +
                "    \"website\": \"https://simplesolution.dev\",\n" +
                "    \"address\": {\n" +
                "      \"street\": \"Simple Street\",\n" +
                "      \"city\": \"City Name\",\n" +
                "      \"country\": \"Country Name\"\n" +
                "    }\n" +
                "  },\n" +
                "  {\n" +
                "    \"firstName\": \"Java\",\n" +
                "    \"lastName\": \"Tutorial\",\n" +
                "    \"email\": \"java@simplesolution.dev\",\n" +
                "    \"website\": \"https://simplesolution.dev\",\n" +
                "    \"address\": {\n" +
                "      \"street\": \"Test Street\",\n" +
                "      \"city\": \"City Name\",\n" +
                "      \"country\": \"Country Name\"\n" +
                "    }\n" +
                "  },\n" +
                "  {\n" +
                "    \"firstName\": \"Gson\",\n" +
                "    \"lastName\": \"Learn\",\n" +
                "    \"email\": \"gson@simplesolution.dev\",\n" +
                "    \"website\": \"https://simplesolution.dev/tag/gson\",\n" +
                "    \"address\": {\n" +
                "      \"street\": \"Gson Street\",\n" +
                "      \"city\": \"City Name\",\n" +
                "      \"country\": \"Country Name\"\n" +
                "    }\n" +
                "  }\n" +
                "]";

        Gson gson = new Gson();
        Type type = new TypeToken<List<Customer>>(){}.getType();
        List<Customer> customers = gson.fromJson(jsonString, 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 😊