Jackson – Marshal and Unmarshal Java Objects to JSON

This Jackson tutorial will teach us to use Jackson ObjectMapper to read and write JSON data into Java Objects.

1. Setting Up Jackson

To include Jackson library in our project, we should include jackson-databind dependency which internally pulls the other two needed dependencies i.e. jackson-annotations and jackson-core.

We can find the latest version from the maven site.

<properties>
      <jackson.version>2.13.0</jackson.version>
</properties>

<dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>${jackson.version}</version>
</dependency>     
implementation 'com.fasterxml.jackson.core:jackson-databind:2.13.0'

After importing Jackson, we can start using ObjectMapper class for marshalling and unmarshalling the JSON.

ObjectMapper mapper = new ObjectMapper();

//Java Object -> JSON
String json = mapper.writeValueAsString(pojoInstance);

//JSON -> Java Object
Pojo instance = mapper.readValue(json, Pojo.class);

2. ObjectMapper class

The ObjectMapper is the main class used for data-binding. It comes with several reader/writer methods to perform the conversion from/to Java and JSON. It will use instances of JsonParser and JsonGenerator for implementing actual reading/writing of JSON.

ObjectMapper provides functionality for reading and writing JSON in two forms:

  • to and from basic POJOs
  • to and from a general-purpose JSON Tree Model

ObjectMapper also acts as a factory for more advanced ObjectReader and ObjectWriter classes. These classes are builder pattern-style objects and pretty much do the same thing as ObjectMapper. ObjectMapper instances are fully thread-safe provided that ALL configuration of the instance occurs before ANY read or write calls.

The main methods in the ObjectMapper class are:

  • canDeserialize(Class type) – to check whether mapper can deserialize an instance of given Class.
  • canSerialize(Class type) – to check whether mapper can serialize an instance of given Class.
  • configure(SerializationFeature f, boolean state) – changes state of an on/off serialization feature.
  • configure(DeserializationFeature f, boolean state) – changes state of an on/off deserialization feature.
  • configure(JsonParser.Feature f, boolean state) – changes state of specified feature for parser instance.
  • copy() – creates a new ObjectMapper instance that has same initial configuration as original instance.
  • readValue()reads the JSON from various sources such as byte array, File, InputStream, Reader, URL or String.
  • writeValue()writes to serialize JSON to various formats such as OutputStream, Writer, POJO or File.

See Also: Marshalling and Unmarshalling XML to Java Objects

3. Marshalling Java Objects to JSON

3.1. Simple Usage

Jackson is pretty much straightforward in converting between simple POJO objects to JSON strings. It involves only two steps:

  • Create instance of com.fasterxml.jackson.databind.ObjectMapper
  • Use objectMapper.writeValueAsString() method to convert POJO to JSON
public class Article 
{
	private Long id;
	private String title;
	private List<String> tags;

        //Setters, getters and constructors are hidden for brevity
}
ObjectMapper mapper = new ObjectMapper();

Article article = new Article(1L, "Test Title", Collections.singletonList("Test Tag"));

String json = mapper.writeValueAsString(article);

System.out.println(json);  //{"id":1,"title":"Test Title","tags":["Test Tag"]}

3.2. Pretty Printing

To get the formatted JSON string, use writerWithDefaultPrettyPrinter() method to get the pretty print-enabled writer instance. Or we can simply enable the SerializationFeature.INDENT_OUTPUT in the ObjectMapper class.

ObjectMapper mapper = new ObjectMapper();
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(article);
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);

String json = mapper..writeValueAsString(article);

4. Unmarshalling JSON to Java Objects

4.1. Reading from String

Similar to the writing operation, reading a JSON to a Java object is pretty simple. We need to use the readValue() method of ObjectMapper.

String json = "{\"id\":1,\"title\":\"Test Title\",\"tags\":[\"Test Tag\"]}";

ObjectMapper mapper = new ObjectMapper();
Article newArticle = mapper.readValue(json, Article.class);

System.out.println(newArticle);  //Article [id=1, title=Test Title, tags=[Test Tag]]

4.2. Reading from JSON File

Reading the JSON from a file to a Java object is also pretty much similar to the previous example. We need to use the readValue() method of ObjectMapper.

We only need to replace the first parameter to readValue() method and pass the File instance to it.

Read More: Reading a file from the resources folder

ObjectMapper mapper = new ObjectMapper();

//Reads the file from resources folder
URL url = Jackson2Demo.class.getClassLoader().getResource("article.json");

Article article = mapper.readValue(new File(url.getFile()), Article.class);

System.out.println(article);

Happy Learning !!

Sourcecode Download

Leave a Reply

2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.

Our Blogs

REST API Tutorial