Main Tutorials

Write JSON to a file with Jackson

This article shows you write JSON to a file with Jackson.

Table of contents:

P.S Tested with Jackson 2.17.0

1. Download Jackson

Declare jackson-databind in the pom.xml.

pom.xml

  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.17.0</version>
  </dependency>

2. Define a Java Object

A simple Person class.

ViewCompany.java

package com.mkyong.json.model;

public class Person {

    private String name;
    private int age;

    // getters, setters ad constructors
}

3. Write JSON to a File

We can use ObjectMapper.writeValue(file, object) to write the Person object to a file named person.json.

JsonViewExample.java

package com.mkyong.json.jackson.tips;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mkyong.json.model.Person;

import java.io.File;
import java.io.IOException;

public class WriteJsonToFileExample {

    public static void main(String[] args) {

        Person person = new Person("mkyong", 42);

        ObjectMapper om = new ObjectMapper();

        try {

            // create a file object
            File file = new File("person.json");

            // write JSON to a File
            om.writeValue(file, person);

            System.out.println("Filed saved to: " + file.getAbsolutePath());

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

}

Output

person.json

{"name":"mkyong","age":42}

To write pretty-formatted JSON to a file, try this:


    ObjectMapper om = new ObjectMapper();
    // enable pretty print
    om.writerWithDefaultPrettyPrinter().writeValue(file, person);

Output

person.json

{
  "name" : "mkyong",
  "age" : 42
}

4. Download Source Code

$ git clone https://github.com/mkyong/java-json

$ cd jackson

5. References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments