本文详解如何通过自定义 TypeAdapterFactory,在 Gson 中实现 Kotlin 泛型 Optional 类型的条件序列化:当 isPresent == false 时完全省略字段,即使启用了 serializeNulls();同时指出 Gson 对 Kotlin 可空性与缺失字段处理的固有限制。
本文详解如何通过自定义 typeadapterfactory,在 gson 中实现 kotlin 泛型 optional
在 Kotlin 与 Gson 协同开发中,常需区分「字段未提供(absent)」与「字段明确为 null(present but null)」两种语义——这正是 Optional
要实现真正的“按值跳过序列化”,必须编写自定义 TypeAdapterFactory,拦截 Optional
class OptionalTypeAdapterFactory : TypeAdapterFactory {
override fun <t : any> create(gson: Gson, type: TypeToken<t>): TypeAdapter<t>? {
val rawType = type.rawType
return if (rawType == Optional::class.java) {
val valueType = getActualTypeArgument(type.type, 0) ?: throw IllegalArgumentException("Optional must have a type argument")
val valueAdapter = gson.getAdapter(TypeToken.get(valueType))
object : TypeAdapter<optional>>() {
override fun write(out: JsonWriter, value: Optional?) {
if (value == null || !value.isPresent) {
// 完全跳过写入:不调用 out.nullValue(),也不输出任何键值对
return
}
// isPresent == true → 序列化 value 字段本身(非整个 Optional 对象)
valueAdapter.write(out, value.value)
}
override fun read(`in`: JsonReader): Optional? {
// 注意:反序列化需额外处理缺失/空值逻辑(见后文说明)
throw UnsupportedOperationException("Deserialization not covered in basic use case")
}
} as TypeAdapter<t>
} else null
}
private fun getActualTypeArgument(type: Type, index: Int): Type? {
return if (type is ParameterizedType) {
type.actualTypeArguments.getOrNull(index)
} else null
}
}</t></optional></t></t></t>
使用方式如下:
val gson = GsonBuilder()
.registerTypeAdapterFactory(OptionalTypeAdapterFactory())
.serializeNulls() // 即使启用,也不会影响 Optional 的跳过逻辑
.create()
val request = SimpleRequest(
a = 42,
c = Optional(isPresent = true, value = "Hello"),
e = Optional(isPresent = false, value = null) // ← 此字段将完全不出现在 JSON 中
)
val json = gson.toJson(request)
// 输出:{"a":42,"c":"Hello","d":null}
// 注意:b、e 字段均未出现;d 因是 Int? 且为 null,仍输出 "d":null(符合 serializeNulls 行为)
✅ 关键机制说明:
- write() 方法中,仅当 value != null && value.isPresent == true 时才调用 valueAdapter.write(),且直接写入 value 的原始值(如 "Hello"),而非 { "isPresent":true, "value":"Hello" };
- isPresent == false 时,不调用 out.name() 或 out.nullValue(),Gson 自动跳过该字段,实现真正意义上的“省略”;
- 该方案与 serializeNulls() 共存无冲突:它只约束 Optional 类型,其他字段(如 d: Int?)仍遵循全局配置。
⚠️ 重要限制与注意事项:
- Kotlin 支持薄弱:Gson 原生面向 Java,对 Kotlin 数据类默认值、lateinit、委托属性等支持不足(Issue #1657)。建议在 Kotlin 项目中优先考虑 Moshi 或 Jackson with Kotlin module,它们对可空性与缺失字段语义有原生支持;
- 反序列化未覆盖:上述 TypeAdapter.read() 抛出异常,因反序列化需解决歧义问题——JSON 中缺失字段应映射为 isPresent=false 还是使用构造函数默认值?Gson 不提供“字段缺失回调”(Issue #1005),故可靠反序列化需配合 @JsonAdapter 显式标注或改用更灵活的库;
-
泛型擦除应对:getActualTypeArgument() 提取泛型实参,确保嵌套类型(如 Optional
)能正确获取 Int? 的适配器,避免类型不匹配。
总结而言,通过自定义 TypeAdapterFactory,你可在 Gson 中精准控制 Optional










