In this short article, you'll learn how to read JSON data from a file by using the Gson library. Gson is a popular JSON processing library developed and maintained by Google for reading, writing, and parsing JSON data in Java.

Dependencies

To add Gson to your Gradle project, add the following dependency to the build.gradle file:

implementation 'com.google.code.gson:gson:2.8.6'

For Maven, include the below dependency to your pom.xml file:

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

Read JSON File to a Java Map

Suppose you have the following JSON file called user.json:

{
  "name": "John Doe",
  "email": "john.doe@example.com",
  "roles": [
    "Member",
    "Admin"
  ],
  "admin": true
}

To read the above JSON file contents to a Java Map, you can use the fromJson() method from Gson as shown below:

try {
    // create Gson instance
    Gson gson = new Gson();

    // create a reader
    Reader reader = Files.newBufferedReader(Paths.get("user.json"));

    // convert JSON file to map
    Map<?, ?> map = gson.fromJson(reader, Map.class);

    // print map entries
    for (Map.Entry<?, ?> entry : map.entrySet()) {
        System.out.println(entry.getKey() + "=" + entry.getValue());
    }

    // close reader
    reader.close();

} catch (Exception ex) {
    ex.printStackTrace();
}

You should see the following output printed on the console:

name=John Doe
email=john.doe@example.com
roles=[Member, Admin]
admin=true

Read JSON File to a Java Object

Let us first create a simple Java class called User.java to map the JSON object:

public class User {

    public String name;
    public String email;
    private String[] roles;
    private boolean admin;

    public User() {
    }

    public User(String name, String email, String[] roles, boolean admin) {
        this.name = name;
        this.email = email;
        this.roles = roles;
        this.admin = admin;
    }

    // getters and setters, toString() .... (omitted for brevity)
}

The following example shows how you can read the above JSON file into a User object by using the fromJson() method:

try {
    // create Gson instance
    Gson gson = new Gson();

    // create a reader
    Reader reader = Files.newBufferedReader(Paths.get("user.json"));

    // convert a JSON string to a User object
    User user = gson.fromJson(reader,User.class);

    // print user object
    System.out.println(user);

    // close reader
    reader.close();

} catch (Exception ex) {
    ex.printStackTrace();
}

You should see the following output printed on the console:

User{name='John Doe', email='john.doe@example.com', roles=[Member, Admin], admin=true}

Read JSON File to a List of Java Objects

Let us say we have the following JSON file called users.json that contains a JSON array:

[
  {
    "name": "John Doe",
    "email": "john.doe@example.com",
    "roles": [
      "Member",
      "Admin"
    ],
    "admin": true
  },
  {
    "name": "Tom Lee",
    "email": "tom.lee@example.com",
    "roles": [
      "Member"
    ],
    "admin": false
  }
]

You can now read a list of User objects from the above JSON file by using the same fromJson() method, as shown below:

try {
    // create Gson instance
    Gson gson = new Gson();

    // create a reader
    Reader reader = Files.newBufferedReader(Paths.get("users.json"));

    // convert JSON array to list of users
    List<User> users = new Gson().fromJson(reader, new TypeToken<List<User>>() {}.getType());

    // print users
    users.forEach(System.out::println);

    // close reader
    reader.close();

} catch (Exception ex) {
    ex.printStackTrace();
}

Here is the output of the above code:

User{name='John Doe', email='john.doe@example.com', roles=[Member, Admin], admin=true}
User{name='Tom Lee', email='tom.lee@example.com', roles=[Member], admin=false}

For more Gson examples, check out the how to read and write JSON using Gson in Java tutorial.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.