Convert Java Object to JSON using Gson

In this quick guide, you'll learn how to use Gson 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 project, add the following dependency to the build.gradle:

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

User.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:

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:

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

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:

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

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:

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:

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 tutorial.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.