Java Gson write list example

In this example, we will learn how to write a list of JSON objects into a file using Gson library.

Check out top GSON tutorial at Google GSON Tutorial.

Java Gson Maven dependency

This is a Maven dependency for Gson:

Java Gson write list example

The example writes JSON data into an items.json file.
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

class Item {
    private final String name;
    private final int quantity;

    public Item(String name, int quantity) { = name;
        this.quantity = quantity;

public class GsonWriteList {

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

        String fileName = "src/main/resources/items.json";
        try (FileOutputStream fos = new FileOutputStream(fileName);
                OutputStreamWriter isr = new OutputStreamWriter(fos, 
                        StandardCharsets.UTF_8)) {
            Gson gson = new Gson();
            Item item1 = new Item("chair", 4);
            Item item2 = new Item("book", 5);
            Item item3 = new Item("pencil", 1);
            List<Item> items = new ArrayList<>();
            gson.toJson(items, isr);
        System.out.println("Items written to file");
Output: Items written to file.

Free Spring Boot Tutorial - 5 Hours Full Course

Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course