This article shows you write JSON to a file with Jackson.
Table of contents:
- 1. Download Jackson
- 2. Define a Java Object
- 3. Write JSON to a File
- 4. Download Source Code
- 5. References
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
- Jackson Github
- Parse JSON string with Jackson
- Parse JSON Array with Jackson
- Convert Java Objects to JSON with Jackson
The post Write JSON to a file with Jackson appeared first on Mkyong.com.