Exclude null objects from JSON array with Gson

坚强是说给别人听的谎言 提交于 2019-12-23 03:59:10

问题


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: [
    {"key":"value1"},
    null,
    {"key":"value2"}
  ]
}

should result in a List<SomeObject> with 2 items.

How can you do this with Gson?


回答1:


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

  • Gson User Guide - Custom serializers and deserializers



回答2:


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




回答3:


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!



来源:https://stackoverflow.com/questions/27637811/exclude-null-objects-from-json-array-with-gson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!