Gson序列化特定类或字段的null [英] Gson serialize null for specific class or field

查看:358
本文介绍了Gson序列化特定类或字段的null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想序列化特定字段或类的空值。

I want to serialize nulls for a specific field or class.

在GSON中,选项 serializeNulls()适用于整个JSON。

In GSON, the option serializeNulls() applies to the whole JSON.

示例:

class MainClass {
    public String id;
    public String name;
    public Test test;
}

class Test {
    public String name;
    public String value;    
} 

MainClass mainClass = new MainClass();
mainClass.id = "101"
// mainClass has no name.
Test test = new Test();
test.name = "testName";
test.value = null;
mainClass.test = test;    

使用GSON创建JSON:

Creating JSON using GSON:

GsonBuilder builder = new GsonBuilder().serializeNulls();
Gson gson = builder.create();
System.out.println(gson.toJson(mainClass));

当前输出:

{
    "id": "101",
    "name": null,
    "test": {
        "name": "testName",
        "value": null
    }
}

所需输出:

{
    "id": "101",
    "test": {
        "name": "testName",
        "value": null
    }
}

如何实现所需的输出?

首选解决方案将具有以下属性:

Preferred solution would have the following properties:


  • 默认情况下 NOT 序列化空值

  • 序列化具有特定注释的字段的空值。

  • Do NOT serialize nulls by default,
  • Serialize nulls for fields with a specific annotation.

推荐答案

我有接口来检查何时将对象序列化为null:

I have interface to check when object should be serialized as null:

public interface JsonNullable {
  boolean isJsonNull();
}

相应的TypeAdapter(支持只写)

And the corresponding TypeAdapter (supports write only)

public class JsonNullableAdapter extends TypeAdapter<JsonNullable> {

  final TypeAdapter<JsonElement> elementAdapter = new Gson().getAdapter(JsonElement.class);
  final TypeAdapter<Object> objectAdapter = new Gson().getAdapter(Object.class);

  @Override
  public void write(JsonWriter out, JsonNullable value) throws IOException {
    if (value == null || value.isJsonNull()) {
      //if the writer was not allowed to write null values
      //do it only for this field
      if (!out.getSerializeNulls()) {
        out.setSerializeNulls(true);
        out.nullValue();
        out.setSerializeNulls(false);
      } else {
        out.nullValue();
      }
    } else {
      JsonElement tree = objectAdapter.toJsonTree(value);
      elementAdapter.write(out, tree);
    }
  }

  @Override
  public JsonNullable read(JsonReader in) throws IOException {
    return null;
  }
}

按如下方式使用:

public class Foo implements JsonNullable {
  @Override
  public boolean isJsonNull() {
    // You decide
  }
}

在Foo值应序列化为null的类中。请注意,foo值本身必须不为null,否则将忽略自定义适配器注释。

In the class where Foo value should be serialized as null. Note that foo value itself must be not null, otherwise custom adapter annotation will be ignored.

public class Bar {
  @JsonAdapter(JsonNullableAdapter.class)
  public Foo foo = new Foo();
}

这篇关于Gson序列化特定类或字段的null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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