如何配置 gson 以排除 0 个整数值

2022-09-03 16:45:34

我有一个包含大量整数字段的Java类,当我想将它们序列化为json字符串时,由于其中一些字段可能没有值,因此在序列化后,所有整数都得到零作为值!我想配置gson,如果它们没有任何值,则不序列化它们。

例如,我有这个类:

class Example {
   String title = "something";
   int id = 22;
   int userId;
} 

默认情况下,gson会给我这个结果:

{
   "title" : "something",
   "id" : 22,
   "userId" : 0
}

但我不希望当userId的值为0时被序列化。所以 json 应该是:

{
   "title" : "something",
   "id" : 22
}

对于对象,默认情况下gson不会序列化空对象,有没有办法配置gson不序列化0个数字


答案 1

我们必须只使用类(Integer javadoc)。Integer

class Example {
   String title = "something";
   Integer id = 22;
   Integer userId;
}

答案 2

创建此 JSON 类型适配器。它可以在任何您想要忽略写入零值的地方使用。它也可以适应多头,双精度和其他数值类型。还可以将其更改为忽略写入除零以外的值。

是的,我知道自动装箱和取消装箱是隐式使用的,但您无法为泛型类型指定基元类型。

public class IntIgnoreZeroAdapter extends TypeAdapter<Integer> {
    private static Integer INT_ZERO = Integer.valueOf(0);

    @Override
    public Integer read(JsonReader in) throws IOException {
        if (in.peek() == JsonToken.NULL) {
            in.nextNull();
            return 0;
        }

        return in.nextInt();
    }

    @Override
    public void write(JsonWriter out, Integer data) throws IOException {
        if (data == null || data.equals(INT_ZERO)) {
            out.nullValue();
            return;
        }

        out.value(data.intValue());
    }
}

更改您的类以指定 intIgnoreZeroAdapter 作为 int 成员。

class Example {
   String title = "something";

   @JsonAdapter(IntIgnoreZeroAdapter.class)
   int id = 22;

   @JsonAdapter(IntIgnoreZeroAdapter.class)
   int userId;
} 

推荐