Gson序列化特定类或字段的null

时间:2016-02-18 09:17:50

标签: java json gson

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

在GSON中,选项serializeNulls()适用于整个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:

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

如何实现所需的输出?

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

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

5 个答案:

答案 0 :(得分:7)

我有一个类似于Aleksey的解决方案,但是可以应用于任何类中的一个或多个字段(例如Kotlin中的示例):

为应该序列化为null的字段创建新的注释:

@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FIELD)
annotation class SerializeNull

创建一个TypeAdapterFactory来检查类在编写对象时是否具有用该注释注释的字段,并从null中删除JsonTree且没有注释注释的字段:

class SerializableAsNullConverter : TypeAdapterFactory {

    override fun <T : Any?> create(gson: Gson, type: TypeToken<T>): TypeAdapter<T>? {
        fun Field.serializedName() = declaredAnnotations
            .filterIsInstance<SerializedName>()
            .firstOrNull()?.value ?: name
        val declaredFields = type.rawType.declaredFields
        val nullableFieldNames = declaredFields
            .filter { it.declaredAnnotations.filterIsInstance<SerializeNull>().isNotEmpty() }
            .map { it.serializedName() }
        val nonNullableFields = declaredFields.map { it.serializedName() } - nullableFieldNames

        return if (nullableFieldNames.isEmpty()) {
            null
        } else object : TypeAdapter<T>() {
            private val delegateAdapter = gson.getDelegateAdapter(this@SerializableAsNullConverter, type)
            private val elementAdapter = gson.getAdapter(JsonElement::class.java)

            override fun write(writer: JsonWriter, value: T?) {
                val jsonObject = delegateAdapter.toJsonTree(value).asJsonObject
                nonNullableFields
                    .filter { jsonObject.get(it) is JsonNull }
                    .forEach { jsonObject.remove(it) }
                val originalSerializeNulls = writer.serializeNulls
                writer.serializeNulls = true
                elementAdapter.write(writer, jsonObject)
                writer.serializeNulls = originalSerializeNulls
            }

            override fun read(reader: JsonReader): T {
                return delegateAdapter.read(reader)
            }
        }
    }
}

使用您的Gson实例注册适配器:

val builder = GsonBuilder().registerTypeAdapterFactory(SerializableAsNullConverter())

并注释您希望可为空的字段:

class MyClass(val id: String?, @SerializeNull val name: String?)

序列化结果:

val myClass = MyClass(null, null)
val gson = builder.create()
val json = gson.toJson(myClass)

json:

{
    "name": null
}

答案 1 :(得分:4)

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

public interface JsonNullable {
  boolean isJsonNull();
}

相应的TypeAdapter(仅支持只写)

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,否则将忽略自定义适配器注释。

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

答案 2 :(得分:2)

对于那些寻求Java版本的@Joris出色答案的人,下面的代码应该可以解决问题。它基本上只是Kotlin的翻译版本,对属性的序列化名称的获取方式进行了较小的改进,以确保当序列化名称与属性名称不同时,该属性始终有效(请参阅原始答案的注释)。

这是TypeAdapterFactory的实现:

public class NullableAdapterFactory implements TypeAdapterFactory {
    @Override
    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
        Field[] declaredFields = type.getRawType().getDeclaredFields();
        List<String> nullableFieldNames = new ArrayList<>();
        List<String> nonNullableFieldNames = new ArrayList<>();

        for (Field declaredField : declaredFields) {
            if (declaredField.isAnnotationPresent(JsonNullable.class)) {
                if (declaredField.getAnnotation(SerializedName.class) != null) {
                    nullableFieldNames.add(declaredField.getAnnotation(SerializedName.class).value());
                } else {
                    nullableFieldNames.add(declaredField.getName());
                }
            } else {
                if (declaredField.getAnnotation(SerializedName.class) != null) {
                    nonNullableFieldNames.add(declaredField.getAnnotation(SerializedName.class).value());
                } else {
                    nonNullableFieldNames.add(declaredField.getName());
                }
            }
        }

        if (nullableFieldNames.size() == 0) {
            return null;
        }

        TypeAdapter<T> delegateAdapter = gson.getDelegateAdapter(NullableAdapterFactory.this, type);
        TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);

        return new TypeAdapter<T>() {
            @Override
            public void write(JsonWriter out, T value) throws IOException {
                JsonObject jsonObject = delegateAdapter.toJsonTree(value).getAsJsonObject();
                for (String name: nonNullableFieldNames) {
                    if (jsonObject.has(name) && jsonObject.get(name) instanceof JsonNull) {
                        jsonObject.remove(name);
                    }
                }

                out.setSerializeNulls(true);
                elementAdapter.write(out, jsonObject);
            }

            @Override
            public T read(JsonReader in) throws IOException {
                return delegateAdapter.read(in);
            }

        };
    }
}

这是@JsonNullable注释,用于标记目标属性:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface JsonNullable {
}

我在对象类上将其实现为@JsonAdapter(NullableAdapterFactory.class)注释,而不是在TypeAdapterFactory实例上将其注册为GsonBuilder,所以我的对象类看起来像这样:

@JsonAdapter(NullableAdapterFactory.class)
public class Person {
  public String firstName;
  public String lastName;

  @JsonNullable
  public String someNullableInfo;
}

但是,如果需要,另一种方法也应与此代码一起工作。

答案 3 :(得分:0)

创建com.google.gson.TypeAdapter的子类,并使用注释com.google.gson.annotations.JsonAdapter将其注册为必填字段。或使用GsonBuilder.registerTypeAdapter注册。在该适配器中,应实现write(和read)。例如:

public class JsonTestNullableAdapter extends TypeAdapter<Test> {

    @Override
    public void write(JsonWriter out, Test value) throws IOException {
        out.beginObject();
        out.name("name");
        out.value(value.name);
        out.name("value");
        if (value.value == null) {
            out.setSerializeNulls(true);
            out.nullValue();
            out.setSerializeNulls(false);
        } else {
            out.value(value.value);
        }
        out.endObject();
    }

    @Override
    public Test read(JsonReader in) throws IOException {
        in.beginObject();
        Test result = new Test();
        in.nextName();
        if (in.peek() != NULL) {
            result.name = in.nextString();
        } else {
            in.nextNull();
        }
        in.nextName();
        if (in.peek() != NULL) {
            result.value = in.nextString();
        } else {
            in.nextNull();
        }
        in.endObject();
        return result;
    }

}

MainClass中,将带有适配器的JsonAdapter注释添加到Test类字段中:

public static class MClass {
    public String id;
    public String name;
    @JsonAdapter(JsonTestNullableAdapter.class)
    public Test test;
}

System.out.println(new Gson.toJson(mainClass))的输出是:

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

答案 4 :(得分:0)

我从这里的各种答案中得到了一些想法。

此实现:

  • 让您在运行时中选择,无论JSON是否为
      • JsonNullable.isJsonNull() == true
      • 发生
    • 不为空
      • JsonNullable.isJsonNull() == false
      • 发生
    • 从JSON中省略(对于HTTP PATCH请求很有用)
        包含Parent的{​​{1}}中的
      • happens字段是JsonNullable
  • 不需要注释
  • 使用null将未处理的工作适当地委派给delegateAdapter

可能需要序列化为null的对象会实现此接口

TypeAdapterFactory

类型适配器工厂,将值序列化为空

/**
 * [JsonNullableTypeAdapterFactory] needs to be registered with the [com.google.gson.Gson]
 * serializing implementations of [JsonNullable] for [JsonNullable] to work.
 *
 * [JsonNullable] allows objects to choose at runtime whether they should be serialized as "null"
 * serialized normally, or be omitted from the JSON output from [com.google.gson.Gson].
 *
 * when [isJsonNull] returns true, the subclass will be serialized to a [com.google.gson.JsonNull].
 *
 * when [isJsonNull] returns false, the subclass will be serialized normally.
 */
interface JsonNullable {

    /**
     * return true to have the entire object serialized as `null` during JSON serialization.
     * return false to have this object serialized normally.
     */
    fun isJsonNull(): Boolean
}

在GSON中注册thr型适配器工厂

class JsonNullableTypeAdapterFactory : TypeAdapterFactory {
    override fun <T : Any?> create(gson: Gson, type: TypeToken<T>): TypeAdapter<T>? {
        return object : TypeAdapter<T>() {
            private val delegateAdapter = gson.getDelegateAdapter(this@JsonNullableTypeAdapterFactory, type)
            override fun read(reader: JsonReader): T = delegateAdapter.read(reader)
            override fun write(writer: JsonWriter, value: T?) {
                if (value is JsonNullable && value.isJsonNull()) {
                    val originalSerializeNulls = writer.serializeNulls
                    writer.serializeNulls = true
                    writer.nullValue()
                    writer.serializeNulls = originalSerializeNulls
                } else {
                    delegateAdapter.write(writer, value)
                }
            }
        }
    }
}

示例对象被序列化为JSON

new GsonBuilder()
    // ....
    .registerTypeAdapterFactory(new JsonNullableTypeAdapterFactory())
    // ....
    .create();