The following example demonstrate how to serialize and deserialize Java object to JSON file. The Jackson’s ObjectMapper
class provides writeValue(File, Object)
and readValue(File, Class<T>)
methods which allow us to write an object into JSON file and read JSON file into an object respectively.
package org.kodejava.jackson;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.kodejava.jackson.support.Artist;
import java.io.File;
import java.io.IOException;
public class ObjectToJsonFile {
public static void main(String[] args) {
Artist artist = new Artist();
artist.setId(1L);
artist.setName("The Beatles");
ObjectMapper mapper = new ObjectMapper();
File file = new File("artist.json");
try {
// Serialize Java object info JSON file.
mapper.writeValue(file, artist);
} catch (IOException e) {
e.printStackTrace();
}
try {
// Deserialize JSON file into Java object.
Artist newArtist = mapper.readValue(file, Artist.class);
System.out.println("newArtist.getId() = " + newArtist.getId());
System.out.println("newArtist.getName() = " + newArtist.getName());
} catch (IOException e) {
e.printStackTrace();
}
}
}
The result of the code snippet are:
newArtist.getId() = 1
newArtist.getName() = The Beatles
Maven Dependencies
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.17.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.17.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.17.1</version>
</dependency>
</dependencies>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024