Parsing JSON Array into List with Gson

This example shows how to parse JSON Array into Java List using the Gson library.
Gson is a Java serialization/deserialization library to convert Java Objects into JSON and back. Gson was created by Google for internal use and later open-sourced.

Java Gson Maven dependency

This is a Maven dependency for Gson.
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.2</version>
</dependency>

Parsing JSON Array into List with Gson Example

In the example, we parse JSON Array into Java List using the Gson library.
package net.javaguides.gson;

import java.io.IOException;
import java.util.List;

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

class Item {

    private String name;
    private int quantity;

    @Override
    public String toString() {
        return "Item{" + "name=" + name + ", quantity=" + quantity + '}';
    }
}

public class GsonReadList {

    public static void main(String[] args) throws IOException {

        Gson gson = new GsonBuilder().create();

        String list = "[ {\"name\":\"chair\",\"quantity\":3}, " +
            "{\"name\":\"book\",\"quantity\":5}, " +
            "{\"name\":\"pencil\",\"quantity\":1} ]\r\n" +
            "";
        List < Item > items = gson.fromJson(list,
            new TypeToken < List < Item >> () {}.getType());

        items.forEach(System.out::println);
    }
}
Output:
Item{name=chair, quantity=3}
Item{name=book, quantity=5}
Item{name=pencil, quantity=1}


Snippet to convert JSON array to List:
 List<Item> items = gson.fromJson(list, 
                new TypeToken<List<Item>>(){}.getType());

Reference

Comments