# How to read and write JSON using Gson in Java

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Nov 29, 2019, updated Oct 14, 2022. Topics: Java, JSON.
Canonical URL: https://attacomsian.com/blog/gson-read-write-json

> A complete guide to learn how to read and write JSON to a file as well as convert a Java Object to JSON and back by using the Gson library.

In my [previous article](https://attacomsian.com/blog/java-read-write-json-files), we looked at reading and writing JSON files in Java using different open-source libraries like [JSON.simple](https://attacomsian.com/blog/json-simple-read-write-json), [Jackson](https://attacomsian.com/blog/jackson-read-write-json), Moshi, and Gson.

In this article, you'll **learn how to read and write JSON using Gson** in detail. [Gson](https://github.com/google/gson) is a popular Java library developed and maintained by Google to convert Java Objects into their JSON representation. 

It can also convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects, including pre-existing objects you do not modify.

## Dependencies

To add Gson to your [Gradle](https://attacomsian.com/blog/install-gradle-on-ubuntu) project, add the following dependency to the `build.gradle` file:

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

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

```xml
<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:

<p class="file-desc"><span>Book.java</span></p>

```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 a parameter:

```java
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:

```json
{"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:

```java
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:

```json
{"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:

```java
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 the below:

```json
[{"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](https://attacomsian.com/blog/jackson-pretty-print-json), you can output pretty-print JSON using Gson:

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

    // create a Gson instance with pretty-printing
    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:

```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:

```java
try {
    // create a 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`:

```java
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 a JSON string to a 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:

```bash
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:

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

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

    // convert a JSON string to a 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:

```java
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 then see the following output:

```bash
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 the same properties and keys, as shown below:

```java
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:

```bash
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:

```java
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 the below:

```json
{"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:

```java
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:

```json
{"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`:

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

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

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

## Exclude Fields with `@Expose` Annotation

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

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

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

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

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

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

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

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

```java
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 the below:

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