Quentin Quentin - 2 months ago 10
Java Question

Exclude null objects from JSON array with Gson

I'm using Gson to parse my REST API calls to Java objects.

I want to filter out null objects in an array, e.g.

list: [

should result in a
with 2 items.

How can you do this with Gson?


Answer: The Custom Serializer

You can add a custom serializer for List.class which would look like:

package com.dominikangerer.q27637811;

import java.lang.reflect.Type;
import java.util.Collections;
import java.util.List;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public class RemoveNullListSerializer<T> implements JsonSerializer<List<T>> {

    public JsonElement serialize(List<T> src, Type typeOfSrc,
            JsonSerializationContext context) {

        // remove all null values

        // create json Result
        JsonArray result = new JsonArray();
        for(T item : src){

        return result;


This will remove the null values from the list using Collections.singleton(null) and removeAll().

Register your Custom Serializer

Now all you have to do is register it to your Gson instance like:

g = new GsonBuilder().registerTypeAdapter(List.class, new RemoveNullListSerializer()).create();

Downloadable & executable Example

You can find this answer and the exact example in my github stackoverflow answers repo:

Gson CustomSerializer to remove Null from List by DominikAngerer

See also