# How to write JSON to a file using Gson in Java

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

> A quick tutorial to learn how to write  JSON data to a file using the Gson library. 

In this short article, you'll **learn how to write JSON data to a file** by using [Gson](https://attacomsian.com/blog/gson-read-write-json). Gson is a popular JSON processing library developed by Google for reading, writing, and parsing JSON data in Java.

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

## Write Java Map to a JSON File

To write a Java `Map` to a JSON file, you can use the `toJson()` method from `Gson` as shown below:

```java
try {
    // create a map
    Map<String, Object> map = new HashMap<>();
    map.put("name", "John Deo");
    map.put("email", "john.doe@example.com");
    map.put("roles", new String[]{"Member", "Admin"});
    map.put("admin", true);

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

    // convert map to JSON File
    new Gson().toJson(map, writer);

    // close the writer
    writer.close();
    
} catch (Exception ex) {
    ex.printStackTrace();
}
```

The above code will produce the following `user.json` JSON file:

```json
{"roles":["Member","Admin"],"name":"John Deo","admin":true,"email":"john.doe@example.com"}
```

## Write Java Object to a JSON File

Let us first create a simple Java class called `User.java` that we will use to convert a Java Object to a JSON file:

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

The following example demonstrates how you can convert and write a `User` object to a JSON file:

```java
try {
    // create user object
    User user = new User("John Doe", "john.doe@example.com",
            new String[]{"Member", "Admin"}, true);

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

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

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

    // close writer
    writer.close();

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

The `user.json` file will have the following JSON data:

```json
{"roles":["Member","Admin"],"name":"John Deo","admin":true,"email":"john.doe@example.com"}
```

## Write a List of Java Objects to a JSON File

Just like a single Java Object, you can also write a list of Java Objects to a JSON file using the same `toJson()` method, as shown below:

```java
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();
}
```

The above code will create the following `users.json` file:

```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}]
```

## Write Java Object to a Pretty Print JSON File

You can use the `GsonBuilder` class to enable the[ pretty-print JSON](https://attacomsian.com/blog/gson-pretty-print-json) output:

```java
try {
    // create user object
    User user = new User("John Doe", "john.doe@example.com",
            new String[]{"Member", "Admin"}, true);

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

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

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

    // close writer
    writer.close();

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

Here is how the `user.json` file looks like after JSON pretty-print is enabled:

```json
{
  "name": "John Doe",
  "email": "john.doe@example.com",
  "roles": [
    "Member",
    "Admin"
  ],
  "admin": true
}
```

For more Gson examples, check out the [how to read and write JSON using Gson in Java](https://attacomsian.com/blog/gson-read-write-json) tutorial.
