【问题标题】:Delete empty arrays in Gson删除 Gson 中的空数组
【发布时间】:2019-02-13 11:11:39
【问题描述】:

我阅读诸如Android GSON deserialize delete empty arrayshttps://medium.com/@int02h/custom-deserialization-with-gson-1bab538c0bfaHow do you get GSON to omit null or empty objects and empty arrays and lists? 之类的主题。

例如,我有一个班级:

data class ViewProfileResponse(
    val success: Int,
    val wallets: List<Wallet>?,
    val contact: Contact?,

    val code: Int,
    val errors: ErrorsResponse?
) {

    data class Contact(
        val countryId: Int,
        val regionId: Int,
        val cityId: Int
    )

    data class Wallet(
        val id: Int,
        val currency: String?,
        val createTime: Int,
        val balance: Float,
        val bonusWallet: BonusWallet?
    ) {

        data class BonusWallet(val id: Int, val balance: Float)
    }

    data class ErrorsResponse(val common: List<String>?)

    class Deserializer : ResponseDeserializable<ViewProfileResponse> {
        override fun deserialize(content: String): ViewProfileResponse? =
            Gson().fromJson(content, ViewProfileResponse::class.java)
    }
}

如您所见,我有一个带有子类的复杂类,每个子类都可以为空。但是,服务器不会在这些字段中发送 null{},而是以 JSON 格式发送 []

我的意思是,我得到的是"contact": [],而不是"contact": null

如何为 Gson 编写自定义反序列化器?这样可以删除空数组,但保留其他类型。我有几十个这样的课程。

【问题讨论】:

    标签: android json gson


    【解决方案1】:

    临时解决方案基于https://stackoverflow.com/a/54709501/2914140

    在这种情况下,反序列化器将如下所示:

    class Deserializer : ResponseDeserializable<ViewProfileResponse> {
    
        private val gson = Gson()
        private val gsonConverter = GsonConverter()
    
        override fun deserialize(content: String): ViewProfileResponse? =
            gson.fromJson(gsonConverter.cleanJson(content), ViewProfileResponse::class.java)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-20
      • 2017-03-16
      相关资源
      最近更新 更多