删除Gson中的空数组

时间:2019-02-13 11:11:40

标签: android json gson

我阅读了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。但是,服务器不是在这些字段中发送null{},而是在JSON中发送[]

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

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

1 个答案:

答案 0 :(得分:0)

临时解决方案基于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)
}