0

I read topics like Android GSON deserialize delete empty arrays, https://medium.com/@int02h/custom-deserialization-with-gson-1bab538c0bfa, How do you get GSON to omit null or empty objects and empty arrays and lists?.

For instance, I have a class:

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)
    }
}

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.

I mean, instead of "contact": null I get "contact": [].

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.

CoolMind
  • 26,736
  • 15
  • 188
  • 224

1 Answers1

0

A temporary solution is based on 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)
}
CoolMind
  • 26,736
  • 15
  • 188
  • 224