Wackaloon
Wackaloon

Reputation: 2365

GSON serialization in Kotlin android, override property

I have a default response class for Retrofit

open class DefaultResponseImpl : DefaultResponse {

    override val error: List<RestError>? get() = meta?.listErrors

    @Expose
    var meta: Meta? = null
}

and this Meta can have some extra fields, so I want to override it with some extra field like this

class SomeResponse : DefaultResponseImpl() {
    @SerializedName("meta")
    @Expose
    val metaLocal: MetaInner? = null

    inner class MetaInner : Meta() {
        @SerializedName("extra_field")
        @Expose
        val field: Long? = null
    }
}

but I am getting error java.lang.IllegalArgumentException: Unable to create converter for class com.responses.SomeResponse

What is wrong? MetaInner is subtype of Meta, I'm not overriding old meta field with another type (which gives error in IDE). I just add another field which must be parsed from the same SerializedName

How can this be achieved in Kotlin?

Upvotes: 1

Views: 960

Answers (1)

Federico De Gioannini
Federico De Gioannini

Reputation: 927

I think it depends on a conflict on "meta" key. In fact SomeResponse class is equivalent to this class:

class SomeResponse : DefaultResponse {

   override val error: List<RestError>? get() = meta?.listErrors

   @Expose
   var meta: Meta? = null

   @SerializedName("meta")
   @Expose
   val metaLocal: MetaInner? = null

   inner class MetaInner : Meta() {
     @SerializedName("extra_field")
     @Expose
     val field: Long? = null
   }
}

It's easy to observe that the key meta is used for both variables meta and metaLocal

You could use a unique class for both requests, using generics in order to pass the type of meta property.

open class DefaultResponseImpl<T> : DefaultResponse {

override val error: List<RestError>? get() {
    if (meta? is Meta?) return meta?.listErrors
    return null
}

@Expose
var meta: T = null
}

Upvotes: 2

Related Questions