Skip to content
Home » Jackson ObjectMapper

Jackson ObjectMapper

1. Overview

In this article, we will learn about the Jackson ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper) class.

By encoding your Java object as a JSON string, you can transfer the Java object over a network or store it in a database or a file.

Serialization is converting your Java object in your application to the JSON format, whereas deserialization allows us to reverse the process by reading the data from an external source and converting it back into the original Java object.

This ObjectMapper class helps you with the serialization and deserialization process in Java:.

  1. Deserialize JSON from sources such as a Java string, stream, byte array, file
  2. Represents the deserialized JSON as a Java object or object graph
  3. Serialize the Java object as a JSON to a file, byte array, java string
  4. Deserialize the JSON into the general purpose JSON tree model

2. Dependencies

To get started, you must add the Jackson library as a dependency in your project. This ObjectMapper class is available in the Jackson databind project.

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.0</version>
</dependency>
Jackson dependencies
Jackson dependencies

The com.fasterxml.jackson.core.databind library dependency pulls in all other required dependencies into your project:

  • jackson-annotations
  • jackson-core

3. Jackson ObjectMapper

The Jackson ObjectMapper provides overloaded functions readValue and writeValue for serialization and deserialization process.

Let’s see examples for each of these.

3.1. Deserialize the Json to object using Jackson ObjectMapper

The overloaded readValue methods can read the Java object from the following JSON sources:

  1. a File
  2. Java string
  3. bytes
  4. Reader
  5. InputStream
  6. JsonParser
  7. URL

Let’s see examples for each of these to understand better

3.1.1. Read the Java object from a JSON file

Consider the result.json file contains the JSON string that pertains to student object. Let’s use the ObjectMapper class readValue method to read the JSON from the file and convert it to the student object.

File file = new File("result.json");
Student fileStudentObject = mapper.readValue(file, Student.class);
System.out.println(fileStudentObject);

3.1.2 Read the Java object from a JSON string

In the below code, the javaStr contains the JSON string and using the function readValue, the JSON string is deserialized to the corresponding Java object.

String javaStr = "{\"id\":101,\"studentName\":\"John\"}";
System.out.println(mapper.readValue(javaStr, Student.class)); 

Consider your Student class contains only private variables and doesn’t have setters or getters:

public class Student {	
	public Student(long id, String name) {
		this.id = id;
		this.studentName = name;
	}	
	public Student() {
	}

	private long id;
	private String studentName;
	
	@Override
	public String toString() {
		return "Student [id=" + id + ", studentName=" + studentName + "]";
	}
}

When you try to convert your JSON string to this Java object, then it would cause the following error:

Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field “id” (class com.tedblob.jackson.objectmapper.models.Student), not marked as ignorable (0 known properties: ])
at [Source: (String)”{“id”:101,”studentName”:”John”}”; line: 1, column: 10] (through reference chain: com.tedblob.jackson.objectmapper.models.Student[“id”])

The reason for this error is that Jackson cannot auto-detect the private fields of your Java class. To fix this error, you must either expose your field as public or create setter with public accessibility for your field.

3.1.3. Read the Java object from a JSON byte array

To convert the JSON byte array to a Java object, use the function readValue.

System.out.println(mapper.readValue(studentBytes, Student.class)); 

3.1.4. Read a Java object from a JSON reader

In the below code, the StreamReader contains the JSON string that needs to be parsed. The ObjectMapper’s readValue reads the StringReader JSON and converts it to the Student java object.

String studentStr = "{\"id\":101,\"studentName\":\"John\"}";
Reader reader = new StringReader(studentStr);

Student student = mapper.readValue(reader, Student.class);
System.out.println(student); 

3.1.5. Read a Java object from a JSON InputStream

In the below code, the FileInputStream reads the JSON from a file. Later, this InputStream is passed as an argument to the readValue method that converts the JSON from the input stream to a Student object.

    InputStream inputStream = new FileInputStream("result.json");
    Student inputStreamStudent = mapper.readValue(inputStream, Student.class);
    System.out.println(inputStreamStudent); 

3.1.6. Read a Java object from a JsonParser

The Jackson JsonParser class is a low level JSON parser. You can use the Jackson ObjectMapper to convert the JsonParser to a Java object.

In the below code, parser is a JsonParser object containing the student json. Using the readValue, we converted the JsonParser to the student object.

String studentStr = "{\"id\":101,\"studentName\":\"John\"}";

JsonFactory factory = new JsonFactory();
JsonParser  parser  = factory.createParser(studentStr);
Student parserStudent = mapper.readValue(parser, Student.class);
System.out.println(parserStudent); 

3.1.7. Read a Java object from a URL

Consider your Json resides in a URL. You can use the ObjectMapper to fetch the JSON from the url and convert it to a student object.

In the below code, we are using the file:src/main/resources/result.json as URL. However, you use any valid url here.

    URL url = new URL("file:src/main/resources/result.json");
    Student fileStudentObj = mapper.readValue(url, Student.class);

3.2. Serialize object and write the Json using Jackson ObjectMapper

The writeValue method of the ObjectMapper supports the following souces:

  1. File
  2. String
  3. bytes
  4. OutputStream
  5. Writer
  6. JsonGenerator

3.2.1. Write the Java object to a JSON file

You can use the ObjectMapper class to serialize the Java object to a JSON and write the JSON to a file.

Let’s create an object for the below Student class and convert that object to a JSON using the ObjectMapper class.

public class Student {	
	public Student(long id, String name) {
		this.id = id;
		this.studentName = name;
	}	
	public Student() {
	}
	private long id;
	private String studentName;	
	@Override
	public String toString() {
		return "Student [id=" + id + ", studentName=" + studentName + "]";
	}
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public String getStudentName() {
		return studentName;
	}
	public void setStudentName(String studentName) {
		this.studentName = studentName;
	}	
}

We perform the following steps to convert the student object to a JSON string.

  1. Create an instance of ObjectMapper.
  2. Call the writeValue method of the ObjectMapper class to serialize the student object and write it to a file.
import com.fasterxml.jackson.databind.ObjectMapper;

@SpringBootApplication
public class JacksonObjectMapperApplication implements CommandLineRunner {
	public static void main(String[] args) {
		SpringApplication.run(JacksonObjectMapperApplication.class, args);
	}

	@Override
	public void run(String... args) throws Exception {
		Student student = new Student(101, "John");
		
		ObjectMapper mapper = new ObjectMapper(); 
		File file = new File("result.json");
		
		mapper.writeValue(file, student); 
		System.out.println(file.getAbsolutePath());
	}
}
ObjectMapper json file
ObjectMapper json file

In the above code, we created a file result.json. To the writeValue function, we are passing this file as an argument.

The ObjectMapper's writeValue function serializes the student object and writes it to the result.json file.

3.2.2 Write the Java object as a JSON string

You can use the function writeValueAsString to convert the Java object to a JSON and returns the JSON as a Java string.

String studentStr = objectMapper.writeValueAsString(student);
System.out.println(studentStr); 

3.2.3 Write the Java object to a JSON byte array

To convert the Java POJO object to a JSON and get the resultant JSON as a byte array, use the function writeValueAsBytes.

byte[] studentBytes = mapper.writeValueAsBytes(student);

3.2.4. Write Java object to outputstream

You can convert the Java object to Json and write it to the Java OutputStream.

In the below code, the writeValue converts the student object to Json and writes it to the OutputStream.

    Student student = new Student(101, "John");
    OutputStream os = new FileOutputStream("resultos.json");
    mapper.writeValue(os, student);

3.2.5. Write Java object to Writer

You can use the writeValue method to convert and write the Java object to the Writer object.

Student student = new Student(101, "John");
Writer writer = new OutputStreamWriter(System.err);
mapper.writeValue(writer, student);
Jackson ObjectMapper to Writer stream
Jackson ObjectMapper to Writer stream

In the above code, we have created an OutputStreamWriter with the standard error stream as output target.

The writeValue takes the student object and converts it to Json.

Then, the converted Json is written to the standard error stream as shown in the screenshot.

Here, the output destination is console.

3.2.6. Serialize object and write Json to JsonGenerator

You can use the ObjectMapper to convert the student object to Json and also write it to the JsonGenerator.

Student student = new Student(101, "John");
JsonFactory factory = new JsonFactory();
    
JsonGenerator generator = factory.createGenerator(
        new File("resultgen.json"), JsonEncoding.UTF8);
mapper.writeValue(generator, student);
ObjectMapper to JsonGenerator file
ObjectMapper to JsonGenerator file

5. Conclusion

In this article, we have seen various scenarios where we can use the Jackson library’s ObjectMapper class.

13 thoughts on “Jackson ObjectMapper”

  1. Pingback: Jackson JsonGenerator - TedBlob

  2. Pingback: Jackson JsonParser - TedBlob

  3. Pingback: Jackson change the name of a property - TedBlob

  4. Pingback: Jackson @JsonIgnoreProperties and @JsonIgnore - TedBlob

  5. Pingback: Jackson parse as Array / List of objects - TedBlob

  6. Pingback: Jackson Ignore null fields - TedBlob

  7. Pingback: Jackson UnrecognizedPropertyException: field Ignorable - TedBlob

  8. Pingback: Jackson serialize/deserialize private fields - TedBlob

  9. Pingback: Jackson deserialize snake case to camel case - TedBlob

  10. Pingback: Jackson JsonMappingException - No serializer found for class - TedBlob

  11. Pingback: Jackson Unrecognized field, not marked as ignorable - TedBlob

  12. Pingback: Jackson Serialization order - TedBlob

  13. I hava a table save jsonString, it like this {“id”:1,”data”:{“a”:1,”b”:2}},but when I using mybatis get it, then put it into a pojo,like

    Map rs = mapBase.query(sql, values);
    ObjectNode a = new ObjectMapper().createObjectNode();
    a.putPOJO(“key”,rs);

    the jackson add “\” into the result. so when the result come to web, it has changed into {“key”: “{\”id\”:1,\”data\”:{\”a\”:1,\”b\”:2}}”}. How can I resolve this problem, not add “\”.

Leave a Reply

Your email address will not be published. Required fields are marked *