12 min read read
create a json file in javacreate json in javajava json examplewrite json file in javajava json tutorialgenerate json file javaorg.json java examplegson java tutorialjava json best practiceshow-to guidetutorial

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

Imad Uddin

Full Stack Developer

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

If you've ever worked with Java and needed to save structured data, send something to an API, or write a config file, chances are you've run into JSON. It's one of those things that seems straightforward on the surface, but the first time you actually try to create a JSON file programmatically in Java, you realize there's more to it than just writing curly braces to a text file.

I remember the first time I needed to generate JSON from a Java application. I spent way too long trying to manually build strings with escaped quotes before I discovered that libraries exist to handle all of that cleanly. So if you're in that same boat right now, this guide is for you. We'll walk through three popular libraries for creating JSON files in Java: Jackson, Gson, and JSON-P. Each one has its strengths, and by the end of this you'll know which one fits your project best.

What JSON Actually Is (Quick Refresher)

JSON stands for JavaScript Object Notation, and despite the name, it has nothing to do with running JavaScript. It's just a text format for representing structured data using key-value pairs. You've probably seen it already if you've worked with any web API or opened a package.json file.

Here's what a basic JSON object looks like:

JSON
{
  "name": "Alice",
  "age": 20,
  "isStudent": true,
  "hobbies": ["reading", "coding"]
}

That's it. Objects use curly braces, arrays use square brackets, strings go in double quotes, and numbers and booleans stand on their own. It's readable, it's compact, and nearly every programming language on the planet can parse it.

In Java, creating a JSON file means building this kind of structure in memory using objects or maps, then writing it out to a .json file. The tricky part isn't the concept. It's picking the right tool and avoiding the pitfalls that trip up beginners.

Why You'd Want to Create JSON Files in Java

Java shows up everywhere: enterprise backends, Android apps, batch processing systems, microservices. And in all of those contexts, JSON is the go-to format for moving data around. Here are the most common reasons you'd need to generate JSON files:

Storing application data. Think user profiles, saved settings, cached results. JSON is lightweight enough that you can read and write it without pulling in a full database for simpler use cases.

Communicating with APIs. If your Java app talks to any REST service, you're sending and receiving JSON. Being able to construct well-formed JSON programmatically is essential.

Configuration files. A lot of modern tooling reads config from JSON. If your app generates or manages configs for other systems, you'll need to produce valid JSON output.

Exporting data. Sometimes you just need to dump structured data into a file that other tools or people can consume. JSON is one of the most portable formats for that.

Setting Up Your Java Development Environment

Before we write any code, let's make sure your environment is ready. If you've already got Java and an IDE 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:

Bash
java -version

You should see something like

java version "17.0.8"
. If you get "command not found," double check that Java is in your system's PATH.

Picking an IDE

You can technically write Java in Notepad, but I wouldn't recommend it. Any of these will make your life much easier:

IntelliJ IDEA Community Edition is my personal favorite. It's free, the autocomplete is excellent, and Maven/Gradle integration works out of the box.

Eclipse has been around forever and has a massive plugin ecosystem. It's free and gets the job done.

VS Code with the Java Extension Pack is surprisingly capable if you prefer a lighter editor.

Creating a Project

Open your IDE, create a new Java project, and make sure it's pointing at your installed JDK. If you're using Maven (which I'd recommend for dependency management), you'll want a standard project structure with a pom.xml. Name it something like

JsonTutorial
and you're ready to go.

Three 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 the library I reach for most often. It's battle-tested, performant, 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:

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.java
:

Java
import 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
file in your project directory:

JSON
{
  "name": "Alice",
  "age": 20,
  "isStudent": true,
  "hobbies": ["reading", "coding"]
}

What's Happening Here

The

HashMap
is acting as our JSON object. Each
put()
call adds a key-value pair. The
Arrays.asList()
call creates the array for hobbies.

ObjectMapper
is Jackson's central class. It handles all the serialization, converting your Java objects into JSON text. The
writeValue()
method takes a File and any Java object (maps, lists, POJOs) and writes the JSON representation directly to disk.

One thing I really like about Jackson is that it works with actual Java classes too. Instead of using a Map, you could define a

Student
class with fields and annotations, and Jackson will serialize it just the same. That approach is cleaner for larger projects where you want type safety.

Pretty Printing with Jackson

By default, Jackson writes compact JSON (no whitespace). If you want readable output, swap out the write call:

Java
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:

XML
<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.java
:

Java
import 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
:

JSON
{
  "name": "Bob",
  "age": 22,
  "isStudent": true,
  "hobbies": ["gaming", "music"]
}

What's Happening Here

GsonBuilder
lets you configure how Gson behaves before creating the actual
Gson
instance. Calling
setPrettyPrinting()
means the output will be nicely indented right from the start, which is something you have to opt into separately with Jackson.

The

toJson()
method takes your data and a
FileWriter
, and handles the serialization and file writing in one shot. Notice there's no intermediate step of creating a File object like with Jackson. Gson writes directly through the writer.

One 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):

XML
<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.java
:

Java
import 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
:

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()
and then chain
.add()
calls to construct your JSON object piece by piece. For arrays, you nest a
Json.createArrayBuilder()
inside.

The

JsonWriter
class handles output. It's separate from the builder, which keeps construction and writing decoupled.

Honestly, JSON-P is more verbose than Jackson or Gson for everyday use. But it has its place. If you're working in a Java EE environment that already uses this API, or if you want very granular control over JSON construction, it's worth knowing. It's also useful as a learning tool because you can see exactly how each piece of the JSON structure is assembled.

Comparing the Three Libraries

Here's a straightforward breakdown to help you decide:

LibraryEase of UsePerformanceBest For
JacksonModerateHighProduction apps, enterprise projects, complex object graphs
GsonVery EasyModerateQuick projects, learning, small to medium apps
JSON-PModerateLowerJava EE environments, educational purposes

My general advice: start with Gson if you're learning. Move to Jackson once you're comfortable and need better performance or features like annotations and streaming. Use JSON-P mainly if your project already depends on it.

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:

Java
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:

JSON
{
  "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 throwaway scripts, I'd recommend defining actual Java classes rather than using HashMaps. It gives you type safety, better IDE support, and cleaner code.

Here's what that looks like with Jackson:

Java
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:

Java
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

After helping a few colleagues get started with JSON in Java, I've noticed the same problems coming up repeatedly. 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")
to write to your project directory. If you need a specific folder, make sure it exists first with
file.getParentFile().mkdirs()
.

ClassNotFoundException or NoClassDefFoundError. Your library JARs aren't on the classpath. If you're using Maven, run

mvn clean install
and make sure the dependency is in your pom.xml. For manual setups, verify the JARs are added to your IDE's build path.

Unexpected 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()
becomes
"name"
. Typos in method names are a common source of confusion.

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
on one side of the relationship, or configure Jackson to handle cycles with
@JsonIdentityInfo
.

Best Practices Worth Following

Use pretty printing during development, compact in production. Pretty-printed JSON is easier to debug, but the extra whitespace adds up in high-volume systems. Most libraries let you toggle this with a single configuration change.

Validate your output. After generating a JSON file, run it through a validator like JSONLint until you're confident your code produces correct output every time.

Prefer POJOs over Maps for production code. Maps work great for quick experiments, but Java classes give you compile-time checking and make your code self-documenting.

Close your writers. Always close FileWriter and JsonWriter instances, preferably in a finally block or using try-with-resources. Failing to close writers can result in incomplete files or resource leaks.

Handle exceptions properly. The examples above use generic catch blocks for simplicity, but in production code, catch specific exceptions (IOException, JsonProcessingException) and log them appropriately.

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()
pattern gives you nicely formatted output right away.

Do I really need a library, or can I 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 I create JSON without an IDE?

Sure. You can write Java in any text editor and compile with

javac
from the command line. But an IDE with autocomplete and error highlighting will save you a lot of time, especially when working with library APIs.

How do I make sure my JSON output is properly formatted?

Use the pretty printing features built into each library. For Gson, that's

setPrettyPrinting()
. For Jackson, use
writerWithDefaultPrettyPrinter()
. For JSON-P, you can configure the writer factory with
JsonGenerator.PRETTY_PRINTING
.

Jackson 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:

Read More

All Articles