Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson fails to deserialize Kotlin class

I am facing an issue with Jackson while deserializing Kotlin class:

Failure(com.fasterxml.jackson.module.kotlin.MissingKotlinParameterException:
Instantiation of [simple type, class my.package.here.Room]
value failed for JSON property arg0 due to missing (therefore NULL) value for creator
parameter arg0 which is a non-nullable type

 at [Source: (okhttp3.ResponseBody$BomAwareReader); line: 1, column: 40]
 (through reference chain: com.valentun.scheduleit.data.model.response.Room["arg0"]))

Here is the class:

@Parcelize
class Room(val code: String, val name: String, val id: Int) : Parcelable

A am using jakson-koltin-module to let Jaskon handle Kotlin metadata.

Here is relevant piece of build.gradle (:app) file:


implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" #kotlin_version = 1.3.72

implementation('com.squareup.retrofit2:retrofit:2.9.0') {
        exclude module: 'okhttp'
    }

implementation 'com.squareup.retrofit2:converter-jackson:2.9.0'
implementation "com.fasterxml.jackson.module:jackson-module-kotlin:2.11.0"
implementation "com.squareup.okhttp3:okhttp:4.8.0"
implementation "com.squareup.okhttp3:logging-interceptor:4.8.0"

And a piece of JaksonFactory initialization:


private fun createRetrofit(okHttp: OkHttpClient) = Retrofit.Builder()
    .baseUrl(BASE_API_URL)
    .addConverterFactory(JacksonConverterFactory.create(createMapper()))
    .client(okHttp)
    .build()

fun createMapper(): ObjectMapper {
    val mapper = ObjectMapper()

    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
    mapper.registerModule(KotlinModule())

    return mapper
}

I also have R8 enabled. Here is my proguard-rules.pro file:

# ------------ Jackson -----------------

-keep class kotlin.Metadata { *; }

#noinspection ShrinkerUnresolvedReference
-keep class my.package.here.** {
    *;
}

-keepnames class my.package.here.** {
   *;
}

-keepclassmembers class * {
     @com.fasterxml.jackson.annotation.JsonCreator *;
     @com.fasterxml.jackson.annotation.JsonProperty *;
     @com.fasterxml.jackson.databind.annotation.JsonDeserialize *;
}

After some investigation, I found several points:

  1. Kotlin metadata exists in resulting apk's bytecode, meaning proguard rules do work.
  2. The error disappears once I use @JsonProperty on each field of the class

For now, I run out of ideas on how to fix that, will appreciate any help.

like image 952
Valentun Avatar asked Dec 20 '25 04:12

Valentun


1 Answers

another cause of error may be case issues, e.g. JSON snake_case vs. Java/Kotlin camelCase. I had this working automagically before, but now had to explicitly translate cases:

@JsonProperty("token_type")
val tokenType: String,
like image 76
Gregor Avatar answered Dec 21 '25 19:12

Gregor