以下作品:
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
答案 0 :(得分:0)
如果bar json值为null,则应该是这样
json
{
"bar": null
}
应该是
adapter.fromJson("{"bar":null}")
答案 1 :(得分:0)