以下作品:

package com.squareup.moshi.problem

import com.squareup.moshi.JsonClass
import com.squareup.moshi.Moshi

@JsonClass(generateAdapter = true)
data class Foo(
        val bar: String?
)

fun main() {
    val adapter=Moshi.Builder().build().adapter<Foo>(Foo::class.java)
    adapter.fromJson("{}")
}

但是使用列表时失败:
package com.squareup.moshi.problem

import com.squareup.moshi.JsonClass
import com.squareup.moshi.Moshi

@JsonClass(generateAdapter = true)
data class Foo(
        val bar: List<String>?
)

fun main() {
    val adapter=Moshi.Builder().build().adapter<Foo>(Foo::class.java)
    adapter.fromJson("{}")
}

与:
Exception in thread "main" com.squareup.moshi.JsonDataException: Required value 'bar' missing at $
        at com.squareup.moshi.internal.Util.missingProperty(Util.java:605)
        at com.squareup.moshi.problem.FooJsonAdapter.fromJson(FooJsonAdapter.kt:44)
        at com.squareup.moshi.problem.FooJsonAdapter.fromJson(FooJsonAdapter.kt:16)
        at com.squareup.moshi.internal.NullSafeJsonAdapter.fromJson(NullSafeJsonAdapter.java:40)
        at com.squareup.moshi.JsonAdapter.fromJson(JsonAdapter.java:43)
        at com.squareup.moshi.problem.MoshiProblemKt.main(MoshiProblem.kt:13)
        at com.squareup.moshi.problem.MoshiProblemKt.main(MoshiProblem.kt)

如何使其适用于列表?
这是显示问题的存储库:https://github.com/ligi/moshi_problem

最佳答案

问题实际上是moshi中的此错误:

https://github.com/square/moshi/issues/990

帽子提示@cketti,向我指出了这个问题。

关于kotlin - moshi可为空的列表失败,出现 “required value”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58820520/

10-10 17:23