Andrey Mamykin Andrey Mamykin - 3 years ago 223
JSON Question

Kotlin Gson custom deserializer for list

How to register custom Json deserializer in Gson?

When I'm register deserializer in java code all works fine, but when I convert Kotlin to Java - deserializer method not called.

Kotlin register code:

val listType: Type = object : TypeToken<List<Advert>>() {}.type
val gson = GsonBuilder()
.registerTypeAdapter(listType, deserializer)

val retrofit = Retrofit.Builder()

Java code:

Type listType = new TypeToken<List<Advert>>() {}.getType();
Gson gson = new GsonBuilder()
.registerTypeAdapter(listType, deserializer)

Retrofit retrofit = new Retrofit.Builder()

Deserializer declaration:

class AdvertsDeserializer : JsonDeserializer<List<Advert>> {
override fun deserialize(json: JsonElement?, typeOfT: Type?,
context: JsonDeserializationContext?): List<Advert> {

Method calling

// list is List<Advert>
list ->
}, {
error ->

As I understand - problem in type of Json object(listType), or what I'm doing wrong?

Answer Source

The problem is that Kotlin compiler adds a wildcard for List, i. e. List<CharSequense> compiles as List<? extends Charsequence>.

The solution is either to use MutableList

object : TypeToken<MutableList<Advert>>() {}.type

or to supperss wildcard

object : TypeToken<List<@JvmSuppressWildcards Advert>>() {}.type
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download