【问题标题】:Deserialize only few properties仅反序列化少数属性
【发布时间】: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'
...
}

【问题讨论】:

    标签: rest kotlin moshi


    【解决方案1】:

    @Transient注释你想跳过的属性,他们会被moshi省略。

    【讨论】:

    • 它是否有可能知道所有属性都是@Transient,除了我想获得的那些,而不必实际写出所有属性?
    【解决方案2】:

    问题是我没有使用KotlinJsonAdapterFactory()。我不得不添加它:

    val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
    

    而且还在 gradle.build 中,因此它可以作为导入使用:

    implementation("com.squareup.moshi:moshi-kotlin:1.12.0")
    

    完成此操作后,它可以正确解析带有部分 Kotlin 对象的 JSON 数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-11
      • 2021-12-13
      • 1970-01-01
      • 2016-08-15
      • 1970-01-01
      相关资源
      最近更新 更多