删除Gson中的空数组 [英] Delete empty arrays in Gson
问题描述
我阅读了 Android GSON反序列化删除空数组之类的主题, https://medium.com/@int02h/custom-deserialization-with-gson -1bab538c0bfa ,例如,我有一个课:
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中发送[]
.
As you see, I have a complex class with subclasses, any of each can be null. But instead of sending null
or {}
in these fields, a server sends []
in JSON.
我的意思是,我得到的不是"contact": null
.
I mean, instead of "contact": null
I get "contact": []
.
如何为Gson编写自定义解串器?这样可以删除空数组,但保留其他类型.我有几十个这样的课程.
How to write a custom deserializer for Gson? So that empty arrays could be removed, but other types retain. I have tens of those classes.
推荐答案
临时解决方案基于 https://stackoverflow.com /a/54709501/2914140 .
在这种情况下,反序列化器将如下所示:
In this case Deserializer will look like:
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)
}
这篇关于删除Gson中的空数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!