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:.
- Deserialize JSON from sources such as a Java string, stream, byte array, file
- Represents the deserialized JSON as a Java object or object graph
- Serialize the Java object as a JSON to a file, byte array, java string
- 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>
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:
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:
- File
- String
- bytes
- OutputStream
- Writer
- 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.
- Create an instance of
ObjectMapper
. - Call the
writeValue
method of theObjectMapper
class to serialize thestudent
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()); } }
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);
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);
5. Conclusion
In this article, we have seen various scenarios where we can use the Jackson library’s ObjectMapper
class.
Pingback: Jackson JsonGenerator - TedBlob
Pingback: Jackson JsonParser - TedBlob
Pingback: Jackson change the name of a property - TedBlob
Pingback: Jackson @JsonIgnoreProperties and @JsonIgnore - TedBlob
Pingback: Jackson parse as Array / List of objects - TedBlob
Pingback: Jackson Ignore null fields - TedBlob
Pingback: Jackson UnrecognizedPropertyException: field Ignorable - TedBlob
Pingback: Jackson serialize/deserialize private fields - TedBlob
Pingback: Jackson deserialize snake case to camel case - TedBlob
Pingback: Jackson JsonMappingException - No serializer found for class - TedBlob
Pingback: Jackson Unrecognized field, not marked as ignorable - TedBlob
Pingback: Jackson Serialization order - TedBlob
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 “\”.