Write JSON String to File Using Gson Library in Java



Let's learn how to write a JSON string to a file using the Gson library in Java. If you are not familiar with JSON, you can refer to JSON Overview. Gson is a library that can be used to convert Java Objects to a JSON representation. To know more about Gson, refer to the Gson tutorial.

GsonBuilder Class

The primary class to use is Gson, which we can create by calling the new Gson(), and the GsonBuilder class can be used to create a Gson instance. We can write a JSON string to a file using the toJson() method of the Gson class

We cannot use the Gson library without downloading or adding it to the project. Because it is not a part of the Java standard library. But we can still use the Gson library without downloading it. We can use it from the Maven repository.

Let's see how to add the Gson library to our project:

  • First, we need to add the Gson library to our project. If you are using Maven, add this to your pom.xml file:
<dependency>
   <groupId>com.google.code.gson</groupId>
   <artifactId>gson</artifactId>
   <version>2.8.9</version>
</dependency>
  • If you are not using Maven, add a jar file to your project. You can download the jar file from here.
  • Steps to write a JSON string to a file using the Gson library:

    • First, import the Gson library as discussed above.
    • Then create a JSON string.
    • Then we will create an instance of the Gson class.
    • Next, we will create a FileWriter object to write the JSON string to a file.
    • Then we will use the toJson() method of the Gson class to write the JSON string to the file.
    • Finally, we will close the FileWriter object.

    Example

    Following is the code to write a JSON string to a file using the Gson library:

    import com.google.gson.Gson;
    import com.google.gson.GsonBuilder;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Map;
    
    public class WriteJsonToFile {
       public static void main(String[] args) {
          // Create a JSON string
          Map<String, Object> jsonMap = new HashMap<>();
          jsonMap.put("name", "Ansh");
          jsonMap.put("age", 23);
          jsonMap.put("city", "New York");
    
          // Create a Gson instance
          Gson gson = new GsonBuilder().setPrettyPrinting().create();
    
          // Write the JSON string to file
          try (FileWriter fileWriter = new FileWriter("output.json")) {
             gson.toJson(jsonMap, fileWriter);
             System.out.println("JSON string written to file successfully.");
          } catch (IOException e) {
             e.printStackTrace();
          }
       }
    }
    

    Following is the output of the above code:

    JSON string written to file successfully.
    
    Updated on: 2025-05-12T10:22:09+05:30

    1K+ Views

    Kickstart Your Career

    Get certified by completing the course

    Get Started
    Advertisements