PolymorphicJsonAdapterFactory 缺少标签

Jac*_*ula 3 parsing android json kotlin moshi

我试图使用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)

Min*_*nki 6

test_type必须是会话类的字段。

如果test_type不能位于会话类内,则必须为包含特定会话类的 TestResult 的每个变体声明一个类,如下所示:

sealed class TestResultSession(open val testType: String)

@JsonClass(generateAdapter = true)
data class TestResultFirstSession(
    @Json(name = "test_type") override val testType: String,
    @Json(name = "session") val session: FirstSession
) : TestResultSession(testType)

@JsonClass(generateAdapter = true)
data class TestResultSecondSession(
    @Json(name = "test_type") override val testType: String,
    @Json(name = "session") val session: SecondSession
) : TestResultSession(testType)
Run Code Online (Sandbox Code Playgroud)

和你的 moshi 多态适配器:

val moshiFactory = Moshi.Builder()
    .add(
        PolymorphicJsonAdapterFactory.of(TestResultSession::class.java,"test_type")
            .withSubtype(TestResultFirstSession::class.java, "first")
            .withSubtype(TestResultSecondSession::class.java, "second")
    )
    .build()
Run Code Online (Sandbox Code Playgroud)

提供后备始终是一个好习惯,这样在test_type未知的情况下,反序列化就不会失败:

@JsonClass(generateAdapter = true)
data class FallbackTestResult(override val testType: String = "")  : TestResultSession(testType)

val moshiFactory = Moshi.Builder()
    .add(
        PolymorphicJsonAdapterFactory.of(TestResultSession::class.java,"test_type")
            .withSubtype(TestResultFirstSession::class.java, "first")
            .withSubtype(TestResultSecondSession::class.java, "second")
            .withDefaultValue(FallbackTestResult())

    )
    .build()
Run Code Online (Sandbox Code Playgroud)