JakeWharton/retrofit2-kotlin-coroutines-adapter

Null properties in the returned object

Closed this issue · 1 comments

For any objects with no default value (such as int, string, etc), the properties will be null when they could not be obtained from the api's Json response. This is the case even when the properties are NOT nullable. NPE exception is thrown when trying to use them. My retrofit module is the following:

@Module
internal class TestRetrofitModule {

    @Provides
    @RepositoryScope
    fun retrofit(okHttpClient: OkHttpClient, gson: Gson): Retrofit =
            Retrofit.Builder()
                    .client(okHttpClient)
                    .baseUrl("http://localhost:$TEST_API_PORT/api/")
                    .addCallAdapterFactory(CoroutineCallAdapterFactory())
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build()

    @Provides
    @RepositoryScope
    fun gson(): Gson = GsonBuilder().create()

    @Provides
    @RepositoryScope
    fun okHttpClient(): OkHttpClient = OkHttpClient.Builder()
            .build()

    companion object {
        const val TEST_API_PORT = 54055
    }
}

Also, relevant gradle dependencies:

implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.jakewharton.retrofit:retrofit2-kotlin-coroutines-experimental-adapter:1.0.0'

Correct me if I'm wrong but my expectation would be that I get some sort of parsing exception instead of an object with null values for non-null properties.

You should try Moshi and its Kotlin support instead. Gson has no knowledge of Kotlin's nullability. This problem has nothing to do with this library, though. It occurs no matter what adapter you choose to use.