使用Gson从JSON数组中排除空对象 [英] Exclude null objects from JSON array with Gson

查看:210
本文介绍了使用Gson从JSON数组中排除空对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Gson解析对Java对象的REST API调用.

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"}
  ]
}

应该导致包含两个项目的List<SomeObject>.

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

如何用Gson做到这一点?

How can you do this with Gson?

推荐答案

答案:自定义序列化程序

您可以为List.class添加一个自定义序列化器,如下所示:

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;
    }

}

这将使用Collections.singleton(null)removeAll()从列表中删除null值.

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

注册您的自定义序列化程序

现在您所要做的就是将其注册到您的Gson实例中,例如:

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

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


可下载的&可执行示例

您可以在我的github stackoverflow答案回购中找到此答案和确切的示例:


Downloadable & executable Example

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

Gson CustomSerializer将从列表中删除Null DominikAngerer

这篇关于使用Gson从JSON数组中排除空对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆