Jackson API - Collection serialization and deserialization example

Posted on March 31, 2018


In our last post, we have learned how to use the Jackson API for binding JSON data to Plain Old Java Object (POJO) and vice versa.

This post shows you how to use the Jackson API to serialize and deserialize the java collection objects  such as List, Map etc.

JAR dependencies

Add the following jars to build path of your project, if you are using Eclipse.

  • jackson-databind-2.9.4.jar
  • jackson-core-2.9.4.jar
  • jackson-annotation-2.9.4.jar

Or add the following dependency to pom.xml file, if you are using Maven.

<dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-databind</artifactId>
   <version>2.9.4</version>
</dependency>

Using Jackson API for collection serialization

The quickest method of converting collection object to JSON is using the ObjectMapper’s  writeValueAsString() method.

The following example demonstrates how to convert the List to JSON text.

JacksonListToJson.java

package com.boraji.tutorial.jackson;

import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class JacksonListToJson {
   public static void main(String[] args) throws JsonProcessingException {
      ObjectMapper mapper = new ObjectMapper();
      mapper.enable(SerializationFeature.INDENT_OUTPUT);

      List<String> books = new ArrayList<>();
      books.add("Head First Java");
      books.add("Thinking in Java");
      books.add("Java: A Beginner's Guide");

      String json = mapper.writeValueAsString(books);
      System.out.println(json);
   }
}

Output

[ "Head First Java", "Thinking in Java", "Java: A Beginner's Guide" ]

The following example demonstrates how to convert the Map to JSON text.

JacksonMapToJson.java

package com.boraji.tutorial.jackson;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class JacksonMapToJson {
   public static void main(String[] args) throws JsonProcessingException {
      
      ObjectMapper mapper=new ObjectMapper();
      mapper.enable(SerializationFeature.INDENT_OUTPUT);
      
      Map<String, Integer> days=new HashMap<>();
      days.put("MON", Calendar.MONDAY);
      days.put("TUE", Calendar.TUESDAY);
      days.put("WED", Calendar.WEDNESDAY);
      days.put("THU", Calendar.THURSDAY);
      days.put("FRI", Calendar.FRIDAY);
      days.put("SAT", Calendar.SATURDAY);
      days.put("SUN", Calendar.SUNDAY);
      
      String json=mapper.writeValueAsString(days);
      System.out.println(json);
   }
}

Output

{
  "THU" : 5,
  "TUE" : 3,
  "WED" : 4,
  "SAT" : 7,
  "FRI" : 6,
  "MON" : 2,
  "SUN" : 1
}

The following example demonstrates how to convert the collection of objects to JSON text. 

JacksonCollectionToJson.java

package com.boraji.tutorial.jackson;

import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

class Employee {
   private long empId;
   private String name;
   private List<Address> address =new ArrayList<>();

   //Setter and Getter methods
}

class Address {
   private String city;
   private String country;
   private String type;

   //Setter and Getter methods
}

public class JacksonCollectionToJson {
   public static void main(String[] args) throws JsonProcessingException {
      Employee employee = new Employee();
      employee.setEmpId(010L);
      employee.setName("Sunil Singh Bora");

      Address permanentAddress = new Address();
      permanentAddress.setCity("Delhi");
      permanentAddress.setCountry("India");
      permanentAddress.setType("P");
      
      Address communicationAddress=new Address();
      communicationAddress.setCity("Mumbai");
      communicationAddress.setCountry("India");
      communicationAddress.setType("C");
      
      employee.getAddress().add(permanentAddress);
      employee.getAddress().add(communicationAddress);
      
      ObjectMapper mapper=new ObjectMapper();
      mapper.enable(SerializationFeature.INDENT_OUTPUT);
      String json=mapper.writeValueAsString(employee);
      System.out.println(json);
   }
}

Output

{
  "empId" : 8,
  "name" : "Sunil Singh Bora",
  "address" : [ {
    "city" : "Delhi",
    "country" : "India",
    "type" : "P"
  }, {
    "city" : "Mumbai",
    "country" : "India",
    "type" : "C"
  } ]
}

 

Using Jackson API for collection deserialization

You can use the ObjectMapper’s readValue() method for converting JSON text to collection object.

The following example demonstrates how to convert the JSON text to List.

JacksonJsonToList.java

package com.boraji.tutorial.jackson;

import java.io.IOException;
import java.util.List;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class JacksonJsonToList {
   public static void main(String[] args) throws IOException {
      ObjectMapper mapper = new ObjectMapper();
      mapper.enable(SerializationFeature.INDENT_OUTPUT);

      String json="[ \"Head First Java\", \"Thinking in Java\", \"Java: A Beginner's Guide\" ]";

      @SuppressWarnings("unchecked")
      List<String> books= mapper.readValue(json, List.class);
      for (String book : books) {
         System.out.println(book);
      }
   }
}

Output

Head First Java
Thinking in Java
Java: A Beginner's Guide

The following example demonstrates how to convert the JSON text to Map.

JacksonJsonToMap.java

package com.boraji.tutorial.jackson;

import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class JacksonJsonToMap {
  
   public static void main(String[] args) throws IOException {
      
      ObjectMapper mapper=new ObjectMapper();
      mapper.enable(SerializationFeature.INDENT_OUTPUT);
      
      String json="{" + 
            "  \"THU\" : 5," + 
            "  \"TUE\" : 3," + 
            "  \"WED\" : 4," + 
            "  \"SAT\" : 7," + 
            "  \"FRI\" : 6," + 
            "  \"MON\" : 2," + 
            "  \"SUN\" : 1" + 
            "}";

      @SuppressWarnings("unchecked")
      Map<String, Integer> days = mapper.readValue(json, Map.class);

      for (Entry<String, Integer> day : days.entrySet()) {
         System.out.println(day.getKey() + "=" + day.getValue());
      }
   }
}

Output

THU=5
TUE=3
WED=4
SAT=7
FRI=6
MON=2
SUN=1

The following example demonstrates how to convert the JSON text to collection containing java objects.

JacksonJsonToCollection.java

package com.boraji.tutorial.jackson;

import java.io.IOException;
import java.util.List;

import com.fasterxml.jackson.databind.ObjectMapper;


public class JacksonJsonToCollection {
   public static void main(String[] args) throws IOException {
      
      String json="{" + 
            "  \"empId\" : 8," + 
            "  \"name\" : \"Sunil Singh Bora\"," + 
            "  \"address\" : [ {" + 
            "    \"city\" : \"Delhi\"," + 
            "    \"country\" : \"India\"," + 
            "    \"type\" : \"P\"" + 
            "  }, {" + 
            "    \"city\" : \"Mumbai\"," + 
            "    \"country\" : \"India\"," + 
            "    \"type\" : \"C\"" + 
            "  } ]" + 
            "}";
      
      ObjectMapper mapper=new ObjectMapper();
      
      Employee employee=mapper.readValue(json, Employee.class);
      
      System.out.println("EMP ID : "+employee.getEmpId());
      System.out.println("EMP NAME : "+employee.getName());
      
      List<Address> addresses=employee.getAddress();
      for (Address address : addresses) {
         System.out.println("--------ADDRESS-------------");
         System.out.println("CITY : "+address.getCity());
         System.out.println("COUNTRY : "+address.getCountry());
         System.out.println("TYPE : "+address.getType());
      }
   }
   
}

Output

EMP ID : 8
EMP NAME : Sunil Singh Bora
--------ADDRESS-------------
CITY : Delhi
COUNTRY : India
TYPE : P
--------ADDRESS-------------
CITY : Mumbai
COUNTRY : India
TYPE : C