How to Create a JSON File in Java — Jackson, Gson & JSON-P Examples

java dev.to

Three solid libraries, three different use cases. Here's the fastest path to creating JSON files in Java.

Option 1: Jackson (most popular)

<!-- pom.xml -->
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.15.2</version>
</dependency>
Enter fullscreen mode Exit fullscreen mode
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.util.*;

public class CreateJson {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();

        Map<String, Object> student = new LinkedHashMap<>();
        student.put("name", "Alice");
        student.put("age", 21);
        student.put("courses", List.of("Math", "CS"));

        mapper.writerWithDefaultPrettyPrinter()
              .writeValue(new File("student.json"), student);

        System.out.println("JSON file created.");
    }
}
Enter fullscreen mode Exit fullscreen mode

Option 2: Gson (lightweight, Google)

import com.google.gson.*;
import java.io.*;

Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonObject obj = new JsonObject();
obj.addProperty("name", "Alice");
obj.addProperty("age", 21);

try (Writer writer = new FileWriter("student.json")) {
    gson.toJson(obj, writer);
}
Enter fullscreen mode Exit fullscreen mode

Which to pick?

Library Best for
Jackson Large projects, Spring Boot, complex types
Gson Simple projects, Android, quick scripts
JSON-P Java EE / Jakarta EE standard compliance

Full beginner-to-advanced guide: How to Create a JSON File in Java

Read Full Tutorial open_in_new
arrow_back Back to Tutorials