# Convert Java Object to JSON using Gson

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-convert-java-object-to-from-json

> A quick guide to learn how to convert a Java Object to a JSON string or file and vice versa by using the Gson library.

In this quick guide, you'll learn how to use [Gson](https://attacomsian.com/blog/gson-read-write-json) to convert a Java Object to its JSON representation and vice versa. Gson provides `toJson()` and `fromJson()` methods to convert Java Objects to and from JSON string.

## Dependencies

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

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

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

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

## Convert Java Object to JSON String

To convert a Java Object into a JSON string, you can use the `toJson()` method from the `Gson` class, as shown below:

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

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

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

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

The above code will generate the following JSON string:

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

## Convert Java Object to JSON File

The `toJson()` method also accepts an instance of `Writer` as a second parameter. You can use this parameter to output the JSON directly to a 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 should contain the following JSON data:

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

## Convert JSON String to Java Object

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

```java
try {
    // user as JSON string
    String json = "{\"name\":\"John Doe\",\"email\":\"john.doe@example.com\"," +
            "\"roles\":[\"Member\",\"Admin\"],\"admin\":true}";

    // convert JSON string to Java Object
    User user = new Gson().fromJson(json, User.class);

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

} catch (Exception ex) {
    ex.printStackTrace();
}
```
 
Here is the output of the above code:

```bash
User{name='John Doe', email='john.doe@example.com', roles=[Member, Admin], admin=true}
```

## Convert JSON File to Java Object

The `fromJson()` method also accepts an instance of `Reader` to parse the file content into a Java Object. Here is an example:

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

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

    // convert a JSON string to a User object
    User user = gson.fromJson(reader,User.class);

    // print user object
    System.out.println(user);

    // close reader
    reader.close();

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

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.
