【发布时间】:2021-12-12 06:39:32
【问题描述】:
当使用 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'
...
}
【问题讨论】: