Jackson – Read and Write JSON

In this Jackson tutorial, we will learn to use Jackson ObjectMapper to read and write JSON data into Java Objects.

1. Jackson Dependencies

To include Jackson 2 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'

2. ObjectMapper

ObjectMapper is the main api 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

2.1. Syntax

Use below sample syntax to read JSON and populate java objects.

ObjectMapper mapper = new ObjectMapper();
Object value = mapper.readValue(jsonSource , javaObject);

Use below sample syntax to write java object to JSON string.

ObjectMapper mapper = new ObjectMapper();
Object value = mapper.writeValue(jsonTarget, javaObject);

2.2. Features

ObjectMapper also acts as a factory for more advanced ObjectReader and ObjectWriter classes. These classes are builder pattern style objects 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.

3. Writing 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 pretty print enabled writer instance.

Or we can simply enable the SerializationFeature.INDENT_OUTPUT in the ObjectMapper class.

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

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

//or

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

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

4. Reading JSON

4.1. Reading JSON String to POJO

Similar to write operation, reading a JSON to 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 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

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

2 thoughts on “Jackson – Read and Write JSON”

  1. Hello,

    If use this method

    Employee emp = mapper.readValue(json, Employee.class);
    

    It strict our JSON properties to be identically with POJO properties. How if i have different property? Example :
    In JSON i have first_name but in POJO i must use firstName

    Thank you

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.