在使用Kotlin和Moshi解析api响应时,我收到了一个相当大的JSON对象。
但是,我看到的所有示例都创建了一个要传递给adapter()的对象,其中包含所有属性。然而,我只需要4-5个。
我如何才能做到这一点呢?目前,这不起作用:
val moshi = Moshi.Builder().build()
val jsonAdapter = moshi.adapter(OnLoadUser::class.java)
val onLoadUser = jsonAdapter.nullSafe().lenient().fromJson(data)它会给出这个错误:
E/EventThread: Task threw exception
java.lang.IllegalArgumentException: Cannot serialize Kotlin type com.biz.app.models.OnLoadUser. Reflective serialization of Kotlin classes without using kotlin-reflect has undefined and unexpected behavior. Please use KotlinJsonAdapterFactory from the moshi-kotlin artifact or use code gen from the moshi-kotlin-codegen artifact.
at com.squareup.moshi.ClassJsonAdapter$1.create(ClassJsonAdapter.java:97)
at com.squareup.moshi.Moshi.adapter(Moshi.java:145)
at com.squareup.moshi.Moshi.adapter(Moshi.java:105)它实际上是一个很大的JSON对象,我只需要4个属性:
{
name: 'John Doe',
email: 'john.doe@gmail.com',
token: 'QWERTY',
guid: '1234-5678-ASDF-9012'
...
}发布于 2021-10-27 13:05:35
注释你想用@Transient跳过的属性,它们将被moshi省略。
发布于 2021-10-28 13:26:29
问题是我没有使用KotlinJsonAdapterFactory()。我不得不添加它:
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()并且在gradle.build中,因此它可以作为导入使用:
implementation("com.squareup.moshi:moshi-kotlin:1.12.0")这样做之后,它可以使用部分Kotlin对象正确地解析JSON数据。
https://stackoverflow.com/questions/69730738
复制相似问题