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>
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.");
}
}
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);
}
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