當使用 Kotlin 和 Moshi 決議 api 回應時,我收到了一個相當大的 JSON 物件。
但是,我看到的所有示例都創建了一個物件以傳遞給adapter()包含所有屬性的物件。但是,我只需要其中的 4-5 個。
我怎樣才能做到這一點?目前這不起作用:
val moshi = Moshi.Builder().build()
val jsonAdapter = moshi.adapter(OnLoadUser::class.java)
val onl oadUser = 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: '[email protected]',
token: 'QWERTY',
guid: '1234-5678-ASDF-9012'
...
}
uj5u.com熱心網友回復:
注釋要跳過的屬性@Transient,它們將被 moshi 省略。
uj5u.com熱心網友回復:
問題是我沒有使用KotlinJsonAdapterFactory(). 我不得不添加它:
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
并且還在 gradle.build 中,以便它可以作為匯入使用:
implementation("com.squareup.moshi:moshi-kotlin:1.12.0")
這樣做之后,它可以使用部分 Kotlin 物件正確決議 JSON 資料。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/340208.html
