我试图使用PolymorphicJsonAdapterFactory以获得不同的类型,但总是遇到奇怪的异常:
缺少 test_type 的标签
我的实体:
@JsonClass(generateAdapter = true)
data class TestResult(
@Json(name = "test_type") val testType: TestType,
...
@Json(name = "session") val session: Session,
...
)
Run Code Online (Sandbox Code Playgroud)
这是我的莫西工厂:
val moshiFactory = Moshi.Builder()
.add(
PolymorphicJsonAdapterFactory.of(Session::class.java, "test_type")
.withSubtype(FirstSession::class.java, "first")
.withSubtype(SecondSession::class.java, "second")
)
.build()
Run Code Online (Sandbox Code Playgroud)
json响应的结构:
{
response: [
test_type: "first",
...
]
}
Run Code Online (Sandbox Code Playgroud)