简体   繁体   中英

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, eg

{
  list: [
    {"key":"value1"},
    null,
    {"key":"value2"}
  ]
}

should result in a List<SomeObject> 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>> {

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

        // remove all null values
        src.removeAll(Collections.singleton(null));

        // create json Result
        JsonArray result = new JsonArray();
        for(T item : src){
            result.add(context.serialize(item));
        }

        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

To remove all the null values from a list regardless of their structure, first we need to register a de-serializer with the gson like this

 Gson gson = new GsonBuilder().registerTypeAdapter(List.class, new RemoveNullListDeserializer()).create();

Then the custom de-serializer would remove the null like this

/**
 * <p>
 * Deserializer that helps remove all <code>null</code> values form the <code>JsonArray</code> .
 */
public class RemoveNullListDeserializer<T> implements JsonDeserializer<List<T>>
{
    /**
     * {@inheritDoc}
     */
    @Override
    public List<T> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
    {
        JsonArray jsonArray = new JsonArray();
        for(final JsonElement jsonElement : json.getAsJsonArray())
        {
            if(jsonElement.isJsonNull())
            {
                continue;
            }
            jsonArray.add(jsonElement);
        }

        Gson gson = new GsonBuilder().create();
        List<?> list = gson.fromJson(jsonArray, typeOfT);
        return (List<T>) list;
    }
}

Hope this help others, who want to remove null values from a json array, regardless of the incoming json structure

My answer maybe late but I expect it works. This question can be solved by removing all the null elements in the Java object when deserialize the json string. So first, we define the custom JsonDeserializer for type List

public class RemoveNullListDeserializer<T> implements JsonDeserializer<List<T>> {
    @Override
    public List<T> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        //TODO
    }
}

And then, remove all null elements in the JsonElement. Here we use recursive to handle these potential null elements.

    private void removeNullEleInArray(JsonElement json) {
        if (json.isJsonArray()) {
            JsonArray jsonArray = json.getAsJsonArray();
            for (int i = 0; i < jsonArray.size(); i++) {
                JsonElement ele = jsonArray.get(i);
                if (ele.isJsonNull()) {
                    jsonArray.remove(i);
                    i--;
                    continue;
                }
                removeNullEleInArray(ele);
            }
        } else if (json.isJsonObject()) {
            JsonObject jsonObject = json.getAsJsonObject();
            for (String key : jsonObject.keySet()) {
                JsonElement jsonElement = jsonObject.get(key);
                if (jsonElement.isJsonArray() || jsonElement.isJsonObject()) {
                    removeNullEleInArray(jsonElement);
                }
            }

        }
    }

It's worth noting that only remove the null elements in top class is not enough.

And next step, transfer this method when deserialize.

public class RemoveNullListDeserializer<T> implements JsonDeserializer<List<T>> {
    @Override
    public List<T> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        removeNullEleInArray(json)
        return Gson().fromJson(json, typeOfT)
    }
}

Finally, register the adapter for creating your Gson:

    Gson gson = new GsonBuilder()
                .registerTypeAdapter(List.class, new RemoveNullListDeserializer())
                .create();

Just Over!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM