How to Read JSON from a File Using Gson API

In modern software development, working with JSON (JavaScript Object Notation) is a common requirement, especially when interacting with REST APIs or handling data interchange between systems. JSON is lightweight, easy to read, and easy to write. Java developers can use libraries like Gson to parse JSON into Java objects and vice versa.

In this blog post, we will explore how to read a JSON file and convert it into Java objects using the Gson library.

What is Gson?

Gson is a Java library that can be used to convert Java objects into their JSON representation and vice versa. It was developed by Google and is widely used for working with JSON in Java applications.

You can use Gson to:

  • Parse JSON into Java objects.
  • Serialize Java objects into JSON.
  • Handle complex data structures with nested objects and arrays.

Setting Up Gson

Before we dive into the code, let's first set up the Gson library in your project. If you're using Maven, you can include Gson as a dependency in your pom.xml file:

<dependency>

    <groupId>com.google.code.gson</groupId>

    <artifactId>gson</artifactId>

    <version>2.8.9</version>

</dependency>

If you're not using Maven, you can manually download the Gson jar file from the Gson GitHub page and add it to your project’s build path.

Example JSON File

Let's say we have a JSON file (data.json) containing information about a user:

{

  "name": "John Doe",

  "age": 30,

  "email": "john.doe@example.com",

  "address": {

    "street": "123 Main St",

    "city": "Springfield",

    "zip": "12345"

  },

  "isActive": true

}

Creating Java Classes to Map the JSON Structure

To read this JSON, we need to map it to a corresponding Java object. Here's an example of how we can create Java classes to represent the JSON structure.

User Class

public class User {
    private String name;
    private int age;
    private String email;
    private Address address;
    private boolean isActive;

    // Getters and setters
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getEmail() {
        return email;
    }

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

    public Address getAddress() {
        return address;
    }

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

    public boolean isActive() {
        return isActive;
    }

    public void setActive(boolean active) {
        isActive = active;
    }
}

Address Class

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

    // Getters and setters
    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 getZip() {
        return zip;
    }

    public void setZip(String zip) {
        this.zip = zip;
    }
}

Reading JSON from a File Using Gson

Now that we have our Java classes set up, let’s write the code to read the JSON file and convert it into a Java object.

Main Class

import com.google.gson.Gson;
import java.io.FileReader;
import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        Gson gson = new Gson();

        try (FileReader reader = new FileReader("data.json")) {
            // Deserialize JSON into a User object
            User user = gson.fromJson(reader, User.class);

            // Print out the user details
            System.out.println("Name: " + user.getName());
            System.out.println("Age: " + user.getAge());
            System.out.println("Email: " + user.getEmail());
            System.out.println("Address: " + user.getAddress().getStreet() + ", " + user.getAddress().getCity());
            System.out.println("Active: " + user.isActive());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Explanation of Code

  1. Gson Initialization:

    • We create an instance of Gson using new Gson().
  2. Reading the File:

    • We use FileReader to read the contents of the data.json file.
  3. Deserializing JSON:

    • The fromJson() method is used to deserialize the JSON data into a User object. It automatically maps the JSON fields to the Java object fields based on the names.
  4. Handling Exceptions:

    • The code is wrapped inside a try-catch block to handle IOException in case the file doesn’t exist or there are issues reading it.
  5. Output:

    • Finally, we print the details of the User object to verify the conversion from JSON to Java.

Handling Nested Objects

In the example, the User class has a nested Address object. Gson handles this nested structure automatically, as long as the Java classes reflect the structure of the JSON data. This is why we created a separate Address class for the nested address object.

Followers