你如何让GSON忽略空或空对象并清空数组和列表? [英] How do you get GSON to omit null or empty objects and empty arrays and lists?

查看:2779
本文介绍了你如何让GSON忽略空或空对象并清空数组和列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是Gson,而我处于一种情况,我必须缩小某些Json字符串的大小。我想这样做是为了不让null对象,只有空值,空列表和数组放入Json字符串中。

I am using Gson and I am in a situation in which I have to shrink the size of certain Json strings. I would like to do so by getting it to not put null objects, only empty values, and empty lists and arrays into the Json string.

有没有一种简单的方法做到这一点?

Is there a straightforward way to do that?

让我澄清一下:我希望所有说:emptyProp:{}或emptyArray:[]被跳过。我希望任何只包含空属性的对象都被跳过。

Let me clarify a bit: I want everything that says: emptyProp:{} or emptyArray:[] to be skipped. I want any object that only contains properties that are empty to be skipped.

推荐答案

默认排除空值,只要您不要为你的GsonBuilder设置serializeNulls()。

Null values are excluded by default as long as you don't set serializeNulls() to your GsonBuilder.

空列表的一种方法是创建一个JsonSerializer

A way for empty lists is to create a JsonSerializer

class CollectionAdapter implements JsonSerializer<Collection<?>> {
  @Override
  public JsonElement serialize(Collection<?> src, Type typeOfSrc, JsonSerializationContext context) {
    if (src == null || src.isEmpty()) // exclusion is made here
      return null;

    JsonArray array = new JsonArray();

    for (Object child : src) {
      JsonElement element = context.serialize(child);
      array.add(element);
    }

    return array;
  }
}

然后注册它

Then register it

Gson gson = new GsonBuilder().registerTypeHierarchyAdapter(Collection.class, new CollectionAdapter()).create();

这篇关于你如何让GSON忽略空或空对象并清空数组和列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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