In my previous article, we looked at reading and writing JSON files in Java using different open-source libraries like JSON.simple, Jackson, Moshi, and Gson.

In this article, you'll learn how to read and write JSON using Gson in detail. Gson is a popular Java library, developed and maintained by Google, to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not modify.

Dependencies

To add Gson to your Gradle project, add the following dependency to 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>

Create Java Class

Let us first create a simple Java class for holding the Book information:

Book.java

public class Book {

    private String title;
    private String isbn;
    private long year;
    private String[] authors;

    public Book() {
    }

    public Book(String title, String isbn, long year, String[] authors) {
        this.title = title;
        this.isbn = isbn;
        this.year = year;
        this.authors = authors;
    }

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

Convert Java Object to JSON String

To convert a Java Object to a JSON string, all you need to do is create a new instance of Gson and then call the toJson() method with Java Object as parameter:

try {
    // create book object
    Book book = new Book("Thinking in Java", "978-0131872486", 1998,
            new String[]{"Bruce Eckel"});

    // convert book object to JSON
    String json = new Gson().toJson(book);

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

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

The above code will produce the following JSON string:

{"title":"Thinking in Java","isbn":"978-0131872486","year":1998,"authors":["Bruce Eckel"]}

Convert Java Object to JSON File

The toJson() method also accepts an instance of Writer as a second parameter that you can use to output the JSON directly to a file, as shown below:

try {
    // create book object
    Book book = new Book("Thinking in Java", "978-0131872486", 1998,
            new String[]{"Bruce Eckel"});

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

    // create a writer
    Writer writer = Files.newBufferedWriter(Paths.get("book.json"));

    // convert book object to JSON file
    gson.toJson(book, writer);

    // close writer
    writer.close();

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

The book.json file should contain the following content:

{"title":"Thinking in Java","isbn":"978-0131872486","year":1998,"authors":["Bruce Eckel"]}

Convert List of Java Objects to JSON Array

You can also convert a list of Java Objects to a JSON array using the same toJson() method, as shown below:

try {
    // create books list
    List<Book> books = Arrays.asList(
            new Book("Thinking in Java", "978-0131872486", 1998,
                    new String[]{"Bruce Eckel"}),
            new Book("Head First Java", "0596009208", 2003,
                    new String[]{"Kathy Sierra", "Bert Bates"})
    );

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

    // create a writer
    Writer writer = Files.newBufferedWriter(Paths.get("books.json"));

    // convert books object to JSON file
    gson.toJson(books, writer);

    // close writer
    writer.close();

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

The books.json file should look like below:

[{"title":"Thinking in Java","isbn":"978-0131872486","year":1998,"authors":["Bruce Eckel"]},
{"title":"Head First Java","isbn":"0596009208","year":2003,"authors":["Kathy Sierra","Bert Bates"]}]

Java Object to Pretty Print JSON File

Just like Jackson, you can also output pretty-print JSON using Gson, as shown below:

try {
    // create book object
    Book book = new Book("Thinking in Java", "978-0131872486", 1998,
            new String[]{"Bruce Eckel"});

    // create Gson instance with pretty-print
    Gson gson = new GsonBuilder().setPrettyPrinting().create();

    // create a writer
    Writer writer = Files.newBufferedWriter(Paths.get("book.json"));

    // convert book object to JSON file
    gson.toJson(book, writer);

    // close writer
    writer.close();

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

The book.json file will have the following pretty-print JSON:

{
  "title": "Thinking in Java",
  "isbn": "978-0131872486",
  "year": 1998,
  "authors": [
    "Bruce Eckel"
  ]
}

Convert Java Map to JSON File

Using Gson, you can also serialize a Java Map object to a JSON file as shown below:

try {
    // create book map
    Map<String, Object> map = new HashMap<>();
    map.put("title", "Thinking in Java");
    map.put("isbn", "978-0131872486");
    map.put("year", 1998);
    map.put("authors", new String[]{"Bruce Eckel"});

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

    // create a writer
    Writer writer = Files.newBufferedWriter(Paths.get("book.json"));

    // convert book object to JSON file
    gson.toJson(map, writer);

    // close writer
    writer.close();

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

Convert JSON String to Java Object

To convert a JSON string back to an equivalent Java Object, you can use the fromJson() method from Gson:

try {
    // JSON string
    String json = "{\"title\":\"Thinking in Java\",\"isbn\":\"978-0131872486\"" +
            ",\"year\":1998,\"authors\":[\"Bruce Eckel\"]}";

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

    // convert JSON string to Book object
    Book book = gson.fromJson(json, Book.class);

    // print book
    System.out.println(book);

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

The above code will output the following on the console:

Book{title='Thinking in Java', isbn='978-0131872486', year=1998, authors=[Bruce Eckel]}

Convert JSON File to Java Object

The fromJson() method also accepts an instance of Reader to read and parse the JSON data from a file:

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

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

    // convert JSON string to Book object
    Book book = gson.fromJson(reader, Book.class);

    // print book
    System.out.println(book);

    // close reader
    reader.close();

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

Convert JSON Array to List of Java Objects

The following example shows how to convert a JSON array to a list of Java Objects using the Gson library:

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

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

    // convert JSON array to list of books
    List<Book> books = Arrays.asList(gson.fromJson(reader, Book[].class));

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

    // close reader
    reader.close();

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

You should the see the following output:

Book{title='Thinking in Java', isbn='978-0131872486', year=1998, authors=[Bruce Eckel]}
Book{title='Head First Java', isbn='0596009208', year=2003, authors=[Kathy Sierra, Bert Bates]}

Convert JSON File to Java Map

By using Gson, you can also convert a JSON file to a Java Map with same properties and keys, as shown below:

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

    // create a reader
    Reader reader = Files.newBufferedReader(Paths.get("book.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();
}

The above code will output the following on the console:

year=1998.0
isbn=978-0131872486
title=Thinking in Java
authors=[Bruce Eckel]

JSON Field Naming with @SerializedName Annotation

By default, Gson uses the class field names as JSON property names. With @SerializedName, you can specify a custom JSON property name:

public class Book {

    @SerializedName("book_name")
    private String title;
    private String isbn;
    private long year;
    private String[] authors;
        
    // ...
}

Now if you convert a Book object to JSON, the output should look like below:

{"book_name":"Thinking in Java","isbn":"978-0131872486","year":1998,"authors":["Bruce Eckel"]}

Include Null Fields

By default, Gson ignores null fields while serializing a Java Object to its JSON representation:

try {
    // create book object
    Book book = new Book("Thinking in Java", null, 1998, null);

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

    // convert book object to JSON
    String json = gson.toJson(book);

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

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

The above code will produce the following JSON without null fields:

{"title":"Thinking in Java","year":1998}

To explicitly include the null fields in the final JSON output, you can use the serializeNulls() method from GsonBuilder:

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

Now the JSON output should include null fields too, as shown below:

{"title":"Thinking in Java","isbn":null,"year":1998,"authors":null}

Exclude Fields with @Expose Annotation

Gson provides multiple ways to exclude certain fields while serializing or deserializing JSON. By default, all static and transient fields are excluded.

However, if you can change this default behavior with the excludeFieldsWithModifiers() method. For example, the following configuration excludes static fields only:

Gson gson = new GsonBuilder()
        .excludeFieldsWithModifiers(Modifier.STATIC)
        .create();

If you want to exclude both static and transient, use the following (which is equivalent to default configuration):

Gson gson = new GsonBuilder()
        .excludeFieldsWithModifiers(Modifier.STATIC, Modifier.TRANSIENT)
        .create();

If you want to exclude certain fields explicitly, use the @Expose annotation. It defines which fields to be excluded from serialization and deserialization to JSON. To enable @Expose, you need to create the Gson object like below:

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

With the above configuration, all fields without @Expose will be excluded. Let us add this annotation to the Book class:

public class Book {

    @Expose(serialize = true, deserialize = true)
    private String title;
    @Expose
    private String isbn;
    @Expose(serialize = false, deserialize = true)
    private long year;
    private String[] authors;
        
    // ...
}

Now if you convert the above Java Object to JSON, the output will be like below:

{"title":"Thinking in Java","isbn":"978-0131872486"}

✌️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. Buy me a coffee (cost $3)

Need help to start a new Spring Boot or MEAN stack project? I am available for contract work. Hire me to accomplish your business goals with engineering and design. Let’s talk about your project: hi@attacomsian.com.