In this short article, you'll learn how to write JSON data to a file by using Gson. 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 project, add the following dependency to the build.gradle
file:
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>
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:
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:
{"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:
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:
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:
{"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:
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:
[{"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 output:
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:
{
"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 tutorial.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.