Home » Map Serialization and Deserialization with Jackson

Map Serialization and Deserialization with Jackson

by Online Tutorials Library

Map Serialization and Deserialization with Jackson

Just like Java objects, we can serialize and deserialize Java Map by using Jackson. We can easily serialize and deserialize Map<Object, Object>, Map<Object, String>, and Map<String, String> to or from JSON-formatted strings by using Jackson.

Serialization of Java Map

A process of converting Java objects into a stream of bytes is referred to as Serialization. The stream of bytes can be persisted or shared as needed. Java Map is one of the least intuitive objects to serialize.

Let’s take some examples to understand how we can serialize Maps such as Map<Object, Object>, Map<Object, String>, or Map<String, String> by using Jackson.

SerializeMapExample1.java

Output:

Map Serialization and Deserialization with Jackson

We can also serialize a Map having a Java object as a value by adding some more lines of code in our previous example.

SerializeMapExample2.java

Output:

Map Serialization and Deserialization with Jackson

Let’s take another example to understand how we can serialize Map<Object, Object> into JSON String.

SerializeMapExample3.java

Output:

Map Serialization and Deserialization with Jackson

Deserialization JSON String to Java Map

A process of converting the stream of bytes into a Java object is referred to as deserialization. We can deserialize the JSON data into Maps of different signatures (Map<String, String>, Map<String, Object>, and Map<Object, Object>).

Let’s take an example to understand how we can deserialize JSON String into Map<String, String>.

DeserializeMapExample1.java

Output:

Map Serialization and Deserialization with Jackson

Let’s take another example to understand how we can deserialize JSON String into Map<Object, String>.

DeserializeMapExample2.java

Output:

Map Serialization and Deserialization with Jackson

Let’s take another example to understand how we can deserialize JSON String into Map<Object, Object>.

DeserializeMapExample3.java

Output:

Map Serialization and Deserialization with Jackson


You may also like