Site icon

Serialize non null values of list of objects – Jackson ObjectMapper (example)

Jackson ObjectMapper maven dependencies

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

Program – Serialize non nulls using Jackson ObjectMapper

1.) Person Class:

public class Person {
	public String firstName;
	public String lastName;
	public int age;
	public Person() {		
	}
	public Person(String firstName, String lastName,
				int age) {
		this.firstName = firstName;
		this.lastName = lastName;
		this.age = age;
	}
}

2.) JSONListConverter Class:

We will perform couple of conversions from list of person objects to json.

  1. Convert list of person objects to JSON (Default serialization)
    • Serializing the null values of person objects
  2. Convert list of person objects to JSON
    • Do not serialize the null values of person objects
package org.learn.jackson;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class JSONListConverter 
{
    public static void main( String[] args ) throws IOException
    {
    	ObjectMapper objectMapper = new ObjectMapper();
    	//Set pretty printing of json
    	objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

    	//List of person objects which will be converted to JSON
    	List personList = Stream.of(
					new Person("Mike", "harvey", 34),
				  	new Person()
			  	)
				.collect(Collectors.toList());
    	
    	//1. Convert List Person to JSON (Serializing null values)
    	String arrayToJson = objectMapper.writeValueAsString(personList);
    	System.out.println("1. Convert List of person object to JSON (Serializing null values) :");
    	System.out.println(arrayToJson);    	
    	
    	//ObjectMapper for not serializing null values
    	objectMapper = new ObjectMapper();
    	//Set pretty printing of json
    	objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    	//Setting the serializing feature: do not serialize null values
    	objectMapper.setSerializationInclusion(Include.NON_NULL);
    	arrayToJson = objectMapper.writeValueAsString(personList);
    	System.out.println("2. Convert List of person object to JSON  (do not Serializing null values):");
    	System.out.println(arrayToJson);  
    }
}

Output – Serialize non nulls using Jackson ObjectMapper

1. Convert List of person object to JSON (Serializing null values) :
[ {
  "firstName" : "Mike",
  "lastName" : "harvey",
  "age" : 34
}, {
  "firstName" : null,
  "lastName" : null,
  "age" : 0
} ]
2. Convert List of person object to JSON  (Serializing non null values):
[ {
  "firstName" : "Mike",
  "lastName" : "harvey",
  "age" : 34
}, {
  "age" : 0
} ]
Exit mobile version