杰克逊未能反序列化科特林课

时间:2020-07-23 15:16:13

标签: android kotlin jackson

在反序列化Kotlin课时,我遇到了Jackson的问题:

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"]))

这是课程:

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

A正在使用jakson-koltin-module来让Jaskon处理Kotlin元数据。

以下是相关的build.gradle(:app)文件:


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"

还有一个JaksonFactory初始化:


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
}

我也启用了R8。这是我的proguard-rules.pro文件:

# ------------ 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 *;
}

经过一番调查,我发现了几点:

  1. 在生成的apk的字节码中存在Kotlin元数据,这意味着proguard规则确实有效。
  2. 在班级的每个字段上使用@JsonProperty后,错误消失了

就目前而言,我对如何解决此问题没有足够的想法,将不胜感激。

0 个答案:

没有答案