没有 null 的 Gson 转换器

Gson converter without null

我有两个 api,一个向我发送约会 object,它的 body 就是这样

data class Appointment(
    id:Long = 4,
    name:String = "name"
   ...
)

另一个人应该从我这里收到这个body

{
   name:"name"
}

没有id字段 在 kotlin 代码中,我想将 Id 设置为 null 并且 Gson 应该忽略它,因为它是 null 怎么做 ? 如何在没有空值的情况下将 kotlin class 转换为 json

Gson 默认跳过空值。假设您有一个约会 class,其 ID 可为空:

data class Appointment(
    val id: Long?,
    val name: String,
)

如果id为空,则不会出现在json:

val gson = Gson()
gson.toJson(Appointment(null, "hello")) // => {"name":"hello"}

如果要序列化空值,请在 gson 构建器中使用 serializeNulls() 方法:

val gson = GsonBuilder().serializeNulls().create()
gson.toJson(Appointment(null, "hello")) // => {"id":null,"name":"hello"}