Gson序列化特定类或字段的空值

yquaqz18  于 2022-11-06  发布在  其他
关注(0)|答案(6)|浏览(195)

我想序列化特定字段或类的空值。
在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
    }
}

如何达到预期的产出?
优选的解决方案将具有以下性质:

  • 默认情况下,* 不要 * 序列化空值,
  • 序列化具有特定注解的字段的空值。
drnojrws

drnojrws1#

我有一个类似于Aleksey的解决方案,但它可以应用于任何类中的一个或多个字段(Kotlin中的示例):
为应序列化为null的字段创建新注解:

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

创建一个TypeAdapterFactory,它检查类是否具有使用此注解进行注解的字段,并在写入对象时从JsonTree中删除null字段和未使用注解进行注解的字段:

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)

杰森:

{
    "name": null
}
sg2wtvxw

sg2wtvxw2#

我有接口来检查对象何时应该序列化为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();
}
5f0d552i

5f0d552i3#

对于那些寻找@Joris的优秀答案的Java版本的人来说,下面的代码应该可以做到这一点。它基本上只是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);
                    }
                }

                boolean originalSerializeNulls = out.getSerializeNulls();
                out.setSerializeNulls(true);
                elementAdapter.write(out, jsonObject);
                out.setSerializeNulls(originalSerializeNulls);
            }

            @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)注解,而不是将其注册为GsonBuilder示例上的TypeAdapterFactory,因此我的对象类看起来有点像这样:

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

  @JsonNullable
  public String someNullableInfo;
}

但是,如果愿意的话,其他方法应该也可以与此代码一起使用。

fslejnso

fslejnso4#

创建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
    }
}
c0vxltue

c0vxltue5#

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

  • 允许您在运行时选择JSON是否
  • 零值
  • JsonNullable.isJsonNull() == true时发生
  • 不为空
  • JsonNullable.isJsonNull() == false时发生
  • 从JSON中省略(对HTTP PATCH请求很有用)
  • Parent中包含JsonNullable的发生次数字段为null
  • 不需要注解
  • 通过使用TypeAdapterFactory将未处理的工作正确地委派给delegateAdapter

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

/**
 * [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
}

将值序列化为null的类型适配器工厂

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

向GSON注册三种类型适配器工厂

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

序列化为JSON的示例对象

data class Parent(
    val hello: Child?,
    val world: Child?
)

data class Child(
    val name: String?
) : JsonNullable {
    override fun isJsonNull(): Boolean = name == null
}
ecfsfe2w

ecfsfe2w6#

再加上@Arvoreniad给出的答案
这两项添加是在将输出设置为true之后重置JsonWriter中的null序列化状态,并使用Gson中的字段命名策略获取字段名。

public class SerializeNullTypeAdapterFactory implements TypeAdapterFactory {
    /**
     * {@inheritDoc}
     */
    @Override
    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
        Field[] declaredFields = type.getRawType().getDeclaredFields();
        List<String> nullableFields = new ArrayList<>();
        List<String> nonNullableFields = new ArrayList<>();
        FieldNamingStrategy fieldNamingStrategy = gson.fieldNamingStrategy();

        for (Field declaredField : declaredFields) {
            // The Gson FieldNamingStrategy will handle the @SerializedName annotation + casing conversions
            final String fieldName = fieldNamingStrategy.translateName(declaredField);

            if (declaredField.isAnnotationPresent(JsonNullable.class)) {
                nullableFields.add(fieldName);
            } else {
                nonNullableFields.add(fieldName);
            }
        }

        if (nullableFields.isEmpty()) {
            return null;
        }

        TypeAdapter<T> delegateAdapter = gson.getDelegateAdapter(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();

                nonNullableFields.forEach((var name) -> {
                    if (jsonObject.has(name) && (jsonObject.get(name) instanceof JsonNull)) {
                        jsonObject.remove(name);
                    }
                });

                boolean serializeNulls = out.getSerializeNulls();
                out.setSerializeNulls(true);

                elementAdapter.write(out, jsonObject);

                // Reset default (in case JsonWriter is reused)
                out.setSerializeNulls(serializeNulls);
            }

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

相关问题