Type argument not recognized in Kotlin

Viewed 497

Using gson and retrofit and created a JsonDeserializer.

In java, the class is defined as:

public class Test implements JsonDeserializer<NavigationMenu[]> {...

In Kotlin, it is defined as:

class NavigationMenuArrayDeserializer : JsonDeserializer<Array<NavigationMenu>> {...

The java class is called as expected after being registered with GSON. The Kotlin class is never called.

Retrofit jsonClient = new Retrofit
                .Builder()
                .baseUrl(baseUrl)
                .client(okHttpClient)
                .addConverterFactory(getGsonConverter())
                .build();

...

private GsonConverterFactory getGsonConverter() {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setLenient();
    gsonBuilder.registerTypeAdapter(NavigationMenu[].class, new NavigationMenuArrayDeserializer());
    Gson gson = gsonBuilder.create();
    return GsonConverterFactory.create(gson);
}

Any idea why?

3 Answers

Unfortunately, no suggestion worked for me. I converted the calling class from java to kotlin as calling java class types in kotlin has easily worked for me in the past... and that did the trick.

My original attempt at calling kotlin array class from a java class is still unsuccessful but I was able to get the configuration working so I'm calling this complete.

Converting the configuration java code in the OP to Kotlin did the trick:

private val gsonConverter: GsonConverterFactory
    get() {
        val gsonBuilder = GsonBuilder()
        gsonBuilder.setLenient()
        gsonBuilder.registerTypeAdapter(Array<NavigationMenu>::class.java, NavigationMenuArrayDeserializer())
        val gson = gsonBuilder.create()
        return GsonConverterFactory.create(gson)
    }

I solved a similar issue using the array class. Try something like this:

val clazz = (Array<NavigationMenu>::class).java
gson.fromJson(json, clazz)

I hope this might help.

You may try using TypeToken like this.

private GsonConverterFactory getGsonConverter() {

     val type = object : TypeToken< ArrayList < NavigationMenu >>(){}.getType()

     GsonBuilder gsonBuilder = new GsonBuilder();
     gsonBuilder.setLenient();

     gsonBuilder.registerTypeAdapter(type, new NavigationMenuArrayDeserializer());

     Gson gson = gsonBuilder.create();
     return GsonConverterFactory.create(gson);
}
Related