How to Create a JSON File in Java: Beginner to Advanced Guide

How to Create a JSON File in Java
Creating a JSON file in Java comes up constantly: exporting data, generating configuration files, and sending structured payloads to APIs. The most common beginner mistake is trying to build JSON by hand with string concatenation and escaped quotes, which gets brittle fast.
This guide shows three practical ways to generate a valid
.jsonIf you only need a quick starting point: Gson is the simplest to learn, Jackson is the go-to for most production apps, and JSON-P is useful when you want explicit, builder-style control or you’re already in a Jakarta EE stack.
What JSON Actually Is (Quick Refresher)
JSON (JavaScript Object Notation) is a lightweight text format for structured data. Despite the name, it doesn’t require JavaScript. It’s simply a way to represent key-value pairs and arrays in a format that’s easy to read and easy for machines to parse.
Chances are you’ve already seen JSON in an API response or in files like
package.jsonBasic JSON object structure:
{
"name": "Alice",
"age": 20,
"isStudent": true,
"hobbies": ["reading", "coding"]
}
The structure is simple: objects use curly braces, arrays use square brackets, strings use double quotes, and numbers and booleans are unquoted. Nearly every language can parse JSON, which is why it’s so widely used.
In Java, “creating a JSON file” usually means building this structure in memory (using maps, lists, or plain Java objects) and then serializing it to a
.jsonWhy You'd Want to Create JSON Files in Java
Java shows up everywhere: enterprise backends, Android apps, batch processing systems, and microservices. In all of these contexts, JSON is the go-to format for moving structured data around.
Most common reasons to generate JSON from Java:
- Storing application data: user profiles, saved settings, cached results. JSON is lightweight enough for simple storage without pulling in a full database.
- Communicating with APIs: most REST services expect JSON requests and return JSON responses, so creating well-formed payloads matters.
- Configuration files: plenty of modern tools read configuration from JSON, and some apps generate or manage those configs programmatically.
- Exporting data: JSON is a portable way to share structured data with other systems, tools, or teammates.
Setting Up Your Java Development Environment
Before writing any code, make sure the environment is ready. If Java and an IDE are already set up, feel free to skip ahead.
Installing the JDK
You need the Java Development Kit to compile and run Java programs. Grab the latest LTS version (JDK 17 or 21 are both solid choices) from either the Oracle JDK website or OpenJDK.
After installing, open a terminal and run:
java -version
You should see something like
java version "17.0.8"Picking an IDE
Writing Java in a basic text editor works, but an IDE makes project setup and dependency management much smoother. Common choices:
- IntelliJ IDEA Community Edition: free, strong autocomplete, solid Maven and Gradle support.
- Eclipse: long-established, huge plugin ecosystem, and widely used in many Java shops.
- VS Code with the Java Extension Pack: a lighter editor that still provides good Java tooling.
Creating a Project
Open the IDE, create a new Java project, and make sure it’s pointing at the installed JDK. If the project uses Maven for dependency management, start with the standard structure that includes a
pom.xmlJsonTutorialThree Libraries for Creating JSON in Java
Java doesn't have built-in JSON support in the standard library (unlike Python or JavaScript). That means you'll need a third-party library. The three most popular options are:
Jackson is the workhorse of enterprise Java. It's fast, feature-rich, and supports annotations for mapping Java objects directly to JSON. If you're working on anything production-grade, this is probably what you want.
Gson was built by Google and prioritizes simplicity. The API is clean and intuitive, which makes it a great choice if you're just getting started or working on smaller projects.
JSON-P (javax.json) is the Java EE standard API. It's more verbose than the other two, but it gives you explicit control over every piece of the JSON structure. It's worth knowing about, even if you end up reaching for Jackson or Gson in practice.
Let's walk through each one with full, working examples.
Method 1: Creating a JSON File with Jackson
Jackson is a common default in Java projects. It’s battle-tested, fast, and handles everything from simple maps to deeply nested object graphs.
Adding Jackson to Your Project
If you're using Maven, add this to your pom.xml:
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version>
</dependency>
</dependencies>
If you're not using Maven, download the Jackson JARs from Maven Central and add them to your project's classpath manually.
The Code
Create a file called
CreateJsonWithJackson.javaimport com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class CreateJsonWithJackson {
public static void main(String[] args) {
try {
// Initialize a Map to store JSON data
Map<String, Object> student = new HashMap<>();
student.put("name", "Alice");
student.put("age", 20);
student.put("isStudent", true);
student.put("hobbies", Arrays.asList("reading", "coding"));
// Instantiate Jackson's ObjectMapper
ObjectMapper mapper = new ObjectMapper();
// Write JSON data to a file
mapper.writeValue(new File("student.json"), student);
System.out.println("JSON file created successfully!");
} catch (Exception e) {
System.out.println("Error creating JSON file: " + e.getMessage());
}
}
}
Run this, and you'll find a
student.json{
"name": "Alice",
"age": 20,
"isStudent": true,
"hobbies": ["reading", "coding"]
}
What's Happening Here
The
HashMapput()Arrays.asList()ObjectMapperwriteValue()Jackson also works well with real Java classes. Instead of using a
MapStudentPretty Printing with Jackson
By default, Jackson writes compact JSON (no whitespace). If you want readable output, swap out the write call:
mapper.writerWithDefaultPrettyPrinter().writeValue(new File("student.json"), student);
That gives you nicely indented JSON, which is much easier to read when you're debugging.
Method 2: Creating a JSON File with Gson
Gson is Google's take on JSON serialization, and it's noticeably simpler than Jackson. If you just need to create some JSON and don't need all the advanced features Jackson offers, Gson is a great fit.
Adding Gson to Your Project
Maven dependency:
<dependencies>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version>
</dependency>
</dependencies>
Or grab the JAR from Maven Central.
The Code
Create
CreateJsonWithGson.javaimport com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.FileWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class CreateJsonWithGson {
public static void main(String[] args) {
try {
// Create a Map to hold JSON data
Map<String, Object> student = new HashMap<>();
student.put("name", "Bob");
student.put("age", 22);
student.put("isStudent", true);
student.put("hobbies", Arrays.asList("gaming", "music"));
// Configure Gson for formatted output
Gson gson = new GsonBuilder().setPrettyPrinting().create();
// Write JSON to a file
FileWriter writer = new FileWriter("student_gson.json");
gson.toJson(student, writer);
writer.close();
System.out.println("JSON file created successfully!");
} catch (Exception e) {
System.out.println("Error creating JSON file: " + e.getMessage());
}
}
}
Output in
student_gson.json{
"name": "Bob",
"age": 22,
"isStudent": true,
"hobbies": ["gaming", "music"]
}
What's Happening Here
GsonBuilderGsonsetPrettyPrinting()The
toJson()FileWriterOne thing worth noting: Gson is slightly slower than Jackson for large datasets, but for most applications, the difference is negligible. Where Gson really wins is developer experience. The API is small, the documentation is clear, and you can get productive with it in minutes.
Method 3: Creating a JSON File with JSON-P
JSON-P is the official Java API for JSON Processing. It's part of the Jakarta EE (formerly Java EE) specification, so it follows a more formal, builder-pattern style.
Adding JSON-P to Your Project
You need two Maven dependencies (the API and an implementation):
<dependencies>
<dependency>
<groupId>javax.json</groupId>
<artifactId>javax.json-api</artifactId>
<version>1.1.4</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.1.4</version>
</dependency>
</dependencies>
For non-Maven projects, grab both JARs from Maven Central.
The Code
Create
CreateJsonWithJsonP.javaimport javax.json.*;
import java.io.FileWriter;
public class CreateJsonWithJsonP {
public static void main(String[] args) {
try {
// Build a JSON object
JsonObject student = Json.createObjectBuilder()
.add("name", "Charlie")
.add("age", 21)
.add("isStudent", true)
.add("hobbies", Json.createArrayBuilder()
.add("painting")
.add("hiking")
.build())
.build();
// Write JSON to a file
FileWriter writer = new FileWriter("student_jsonp.json");
JsonWriter jsonWriter = Json.createWriter(writer);
jsonWriter.writeObject(student);
jsonWriter.close();
System.out.println("JSON file created successfully!");
} catch (Exception e) {
System.out.println("Error creating JSON file: " + e.getMessage());
}
}
}
Output in
student_jsonp.json{
"name": "Charlie",
"age": 21,
"isStudent": true,
"hobbies": ["painting", "hiking"]
}
What's Happening Here
JSON-P uses a builder pattern throughout. You call
Json.createObjectBuilder().add()Json.createArrayBuilder()The
JsonWriterJSON-P is more verbose than Jackson or Gson for everyday use, but it has its place. If a project already uses this API (common in Java EE or Jakarta EE environments), or if you want very granular control over how JSON is constructed, it’s a solid option. It’s also useful for learning because it makes each piece of the JSON structure explicit.
Comparing the Three Libraries
Here's a straightforward breakdown to help you decide:
| Library | Ease of Use | Performance | Best For |
|---|---|---|---|
| Jackson | Moderate | High | Production apps, enterprise projects, complex object graphs |
| Gson | Very Easy | Moderate | Quick projects, learning, small to medium apps |
| JSON-P | Moderate | Lower | Java EE environments, educational purposes |
A good rule of thumb: start with Gson when learning or building a small utility, switch to Jackson when you need stronger performance or features like annotations and streaming, and use JSON-P mainly when a project already depends on it or you want explicit builder-style control.
A More Realistic Example: Nested JSON Structures
The examples above are deliberately simple. In real projects, your JSON is going to have nested objects, arrays of objects, and more complex hierarchies. Let's build something closer to what you'd actually encounter.
Here's a library catalog with nested book objects, using Jackson:
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class CreateComplexJson {
public static void main(String[] args) {
try {
// Define book 1
Map<String, Object> book1 = new HashMap<>();
book1.put("title", "The Hobbit");
book1.put("author", "J.R.R. Tolkien");
book1.put("year", 1937);
book1.put("genres", Arrays.asList("Fantasy", "Adventure"));
// Define book 2
Map<String, Object> book2 = new HashMap<>();
book2.put("title", "1984");
book2.put("author", "George Orwell");
book2.put("year", 1949);
book2.put("genres", Arrays.asList("Dystopian", "Fiction"));
// Create library structure
Map<String, Object> library = new HashMap<>();
library.put("libraryName", "City Library");
library.put("books", Arrays.asList(book1, book2));
// Write to JSON file
ObjectMapper mapper = new ObjectMapper();
mapper.writerWithDefaultPrettyPrinter()
.writeValue(new File("library.json"), library);
System.out.println("Complex JSON file created successfully!");
} catch (Exception e) {
System.out.println("Error creating JSON file: " + e.getMessage());
}
}
}
This produces:
{
"libraryName": "City Library",
"books": [
{
"title": "The Hobbit",
"author": "J.R.R. Tolkien",
"year": 1937,
"genres": ["Fantasy", "Adventure"]
},
{
"title": "1984",
"author": "George Orwell",
"year": 1949,
"genres": ["Dystopian", "Fiction"]
}
]
}
This pattern of nesting maps and lists is how you build most real-world JSON structures in Java. Once you get comfortable with it, you can represent pretty much anything: API responses, database exports, configuration hierarchies. The same approach works with Gson and JSON-P too, just with their respective APIs.
Using Java Classes Instead of Maps
For anything beyond a quick prototype, define actual Java classes rather than relying on
HashMapHere's what that looks like with Jackson:
public class Student {
private String name;
private int age;
private boolean isStudent;
private List<String> hobbies;
// Constructor, getters, and setters
public Student(String name, int age, boolean isStudent, List<String> hobbies) {
this.name = name;
this.age = age;
this.isStudent = isStudent;
this.hobbies = hobbies;
}
// Getters
public String getName() { return name; }
public int getAge() { return age; }
public boolean isStudent() { return isStudent; }
public List<String> getHobbies() { return hobbies; }
}
Then your serialization code becomes:
Student student = new Student("Alice", 20, true, Arrays.asList("reading", "coding"));
ObjectMapper mapper = new ObjectMapper();
mapper.writerWithDefaultPrettyPrinter().writeValue(new File("student.json"), student);
Jackson automatically maps the getter methods to JSON keys. You get the same output, but your code is more maintainable and less error-prone. Gson works the same way, serializing fields directly without needing getters.
Troubleshooting Common Issues
The same issues tend to show up when generating JSON in Java. Here’s how to handle them:
FileNotFoundException. This usually means the path you're writing to doesn't exist or you don't have permission. Stick with relative paths like
new File("output.json")file.getParentFile().mkdirs()ClassNotFoundException or NoClassDefFoundError. Your library JARs aren't on the classpath. If you're using Maven, run
mvn clean installUnexpected JSON output. If your JSON looks wrong (wrong field names, missing fields), check that your getter method names match what you expect in the output. Jackson derives JSON keys from getter names, so
getName()"name"Encoding issues. If you see garbled characters in your JSON, make sure you're writing with UTF-8 encoding. Jackson handles this by default, but if you're using FileWriter directly, you might need to wrap it in an OutputStreamWriter with an explicit charset.
Circular references. If you have objects that reference each other (A points to B, B points to A), Jackson will throw a StackOverflowError. Use
@JsonIgnore@JsonIdentityInfoBest Practices Worth Following
- Use pretty printing during development and compact output in production. Pretty JSON is easier to debug, but whitespace adds up in high-volume systems.
- Validate the output. Running generated files through a validator like JSONLint helps catch mistakes early.
- Prefer POJOs over maps in production code. Maps are fine for quick experiments, but Java classes provide compile-time checking and clearer intent.
- Close writers properly. Use try-with-resources (preferred) so and
FileWriteralways get closed.JsonWriter - Handle exceptions deliberately. The examples use broad blocks for simplicity, but production code should catch specific exceptions (for example
catch) and log them appropriately.IOException
Frequently Asked Questions
What's the simplest way to create a JSON file in Java?
Gson has the lowest barrier to entry. You can go from zero to a working JSON file in about 10 lines of code. The
GsonBuilder().setPrettyPrinting().create()Do you really need a library, or can you build JSON strings manually?
You technically can concatenate strings, but please don't. It's error-prone, hard to maintain, and you'll eventually hit edge cases with special characters, escaping, and encoding that the libraries handle automatically.
Can you create JSON without an IDE?
Sure. You can write Java in any text editor and compile with
javacHow do you make sure JSON output is properly formatted?
Use the pretty printing features built into each library. For Gson, that's
setPrettyPrinting()writerWithDefaultPrettyPrinter()JsonGenerator.PRETTY_PRINTINGJackson vs Gson, which should I use?
For learning and small projects, Gson is simpler and quicker to pick up. For production applications, especially ones dealing with large data volumes or complex object hierarchies, Jackson is the better choice. It's faster, more configurable, and has broader ecosystem support (streaming API, XML support, annotation-based mapping).
Can Jackson and Gson serialize Java objects directly?
Yes, both libraries can take a regular Java class instance and convert it to JSON without you having to manually construct maps or builders. Just make sure your class follows JavaBean conventions (or annotate fields appropriately).
Wrapping Up
Creating JSON files in Java is one of those foundational skills that keeps coming up no matter what kind of project you're working on. The good news is that with libraries like Jackson, Gson, and JSON-P doing the heavy lifting, the actual code is pretty straightforward once you understand the basics.
If you're just getting started, grab Gson and experiment with the examples above. Once you're comfortable, try Jackson for a project that needs more horsepower. And if you ever find yourself in a Java EE environment, you'll at least recognize JSON-P when you see it.
The best way to learn this stuff is to build something real. Try creating a JSON export for data you're already working with, or write a small app that generates config files. You'll run into the gotchas firsthand, and that's honestly the fastest way to internalize it all.
Related Resources
- Understand how JSON works at a technical level.
- Combine multiple JSON files with the JSON Merger.
- Learn when to use JSON vs XML vs YAML data formats.
Read More
All Articles
How to Add an Image in JSON: A Comprehensive Guide
Learn how to add an image to a JSON object using URLs, file paths, or base64 encoding. This guide provides examples and best practices for each method.

How to Format JSON in Notepad++: Simple Step-by-Step Guide
Learn how to format JSON in Notepad++ using easy, beginner-friendly steps. This guide covers plugin installation, formatting shortcuts, troubleshooting tips, and real-life examples for developers and non-tech users alike.

How to Merge Excel Files Online (XLS & XLSX): The Complete Guide
Learn how to merge multiple Excel files (XLS & XLSX) into one using a free online tool, Python, VBA macros, and Power Query. Covers append rows, separate sheets, header matching, and best practices for combining spreadsheets.