Read and Write JSON to File using Gson

This article shows how to use Gson to write a Java object to a JSON file and read that JSON file back into a Java object.

Table of contents:

P.S Tested with Gson 2.10.1

1. Download Google Gson

Declare gson in the pom.xml.

pom.xml

    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.10.1</version>
    </dependency>

2. A Java Object

A simple Java object, Person, for testing later.

Person.java

package com.mkyong.json.model;

public class Person {

    private String name;
    private int age;

    // getters, setters, constructors, toString() and etc...
}

3. Write Java object to JSON file using Gson

The following example uses Gson to write a Java object Person to a JSON file.

GsonWriteObjectToJsonExample.java

package com.mkyong.json.gson;

import com.google.gson.Gson;
import com.mkyong.json.model.Person;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

public class GsonWriteObjectToJsonExample {

    public static void main(String[] args) {

        Person person = new Person("mkyong", 42);
        Gson gson = new Gson();

        // write to this file
        try (Writer writer = new FileWriter("person.json")) {

            // Convert the Java object `person` into a JSON data and write to a file
            gson.toJson(person, writer);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}

Output

person.json

{"name":"mkyong1","age":42}

4. Read JSON from a file using Gson

The following example uses Gson to read JSON from a file, convert it into a Person object, and print it out.

GsonReadJsonToObjectExample.java

package com.mkyong.json.gson;

import com.google.gson.Gson;
import com.mkyong.json.model.Person;

import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

public class GsonReadJsonToObjectExample {

    public static void main(String[] args) {

        Gson gson = new Gson();

        // Read JSON from a file
        try (Reader reader = new FileReader("person.json")) {

            // convert the JSON data to a Java object
            Person person = gson.fromJson(reader, Person.class);
            System.out.println(person);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}

Output


Person{name='mkyong1', age=42}

5. Download Source Code

$ git clone https://github.com/mkyong/java-json

$ cd gson

6. References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments