In this quick tutorial, you'll learn how to use the Gson library to convert a JSON array string into a list of Java Objects and vice versa.

Dependencies

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

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>

Example JSON Array

Let us say we have the following JSON array that we want to convert into a list of Java Objects:

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

Convert JSON Array to Java List

To convert the above JSON array to a list of Java Objects, let us first create a simple User class to map JSON fields:

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)
}

Now we can use the fromJson() method from the Gson class to convert the above JSON array to a list of User objects:

try {
    // JSON array
    String json = "[{\"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}]";

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

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

} 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}
User{name='Tom Lee', email='tom.lee@example.com', roles=[Member], admin=false}

To convert the JSON array into an equivalent Java array, you should do the following:

User[] users = new Gson().fromJson(json, User[].class);

If your JSON array is stored in a JSON file, you can still read and parse its content to a list of Java Objects using Gson, as shown below:

List<User> users = new Gson().fromJson(new FileReader("users.json"),
        new TypeToken<List<User>>() {}.getType());

Convert List of Java Objects to JSON Array

The following example demonstrates how to use the toJson() method from the Gson class to convert a list of Java Objects to their JSON representation:

try {
    // create a list of users
    List<User> users = Arrays.asList(
            new User("John Doe", "john.doe@example.com",
                    new String[]{"Member", "Admin"}, true),
            new User("Tom Lee", "tom.lee@example.com",
                    new String[]{"Member"}, false)
    );

    // convert users list to JSON array
    String json = new Gson().toJson(users);

    // print JSON string
    System.out.println(json);

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

You should see the following output:

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

To write a list of Java Objects directly to a JSON file, you can pass an instance of Writer to the toJson() method:

try {
    // create a list of users
    List<User> users = Arrays.asList(
            new User("John Doe", "john.doe@example.com",
                    new String[]{"Member", "Admin"}, true),
            new User("Tom Lee", "tom.lee@example.com",
                    new String[]{"Member"}, false)
    );

    // create writer
    Writer writer = new FileWriter("users.json");

    // convert users list to JSON file
    new Gson().toJson(users, writer);

    // close writer
    writer.close();

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

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.