不带 null 的 Gson 转换器

Posted

技术标签:

【中文标题】不带 null 的 Gson 转换器【英文标题】:Gson converter without null 【发布时间】:2021-10-04 12:57:07 【问题描述】:

我有两个 api,一个向我发送一个 Appointment 对象,它的主体是这样的

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

另一个人应该从我这里得到这个身体


   name:"name"

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

【问题讨论】:

试试这个方法可能对你有帮助futurestud.io/tutorials/… 【参考方案1】:

Gson 默认跳过空值。假设你有一个 id 可以为空的 Appointment 类:

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

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

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

如果要序列化 ​​null,请在 gson builder 中使用serializeNulls() 方法:

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

【讨论】:

以上是关于不带 null 的 Gson 转换器的主要内容,如果未能解决你的问题,请参考以下文章

Gson对象转json时,属性值不存在时转成的null问题??

JSON转换

当从共享prefs获取时,GSON将先前存储的List转换为LinkedTreeMaps的ArrayList

Spring Boot http消息转换器有时会序列化null

Android:使用GSON的对象的JSON失败

Jackson怎样可以把null的属性转换为空字符