【问题标题】:Missing label with PolymorphicJsonAdapterFactoryPolymorphicJsonAdapterFactory 缺少标签
【发布时间】:2020-10-27 00:15:53
【问题描述】:

我正在尝试使用PolymorphicJsonAdapterFactory 来获取不同的类型,但总是遇到奇怪的异常:

缺少 test_type 的标签

我的实体:

@JsonClass(generateAdapter = true)
data class TestResult(
    @Json(name = "test_type") val testType: TestType,
    ...
    @Json(name = "session") val session: Session,
    ...
)

这是我的moshi工厂:

val moshiFactory = Moshi.Builder()
    .add(
        PolymorphicJsonAdapterFactory.of(Session::class.java, "test_type")
            .withSubtype(FirstSession::class.java, "first")
            .withSubtype(SecondSession::class.java, "second")
    )
    .build()

json响应的结构:

 {
   response: [ 
      test_type: "first",
      ...
   ]
}

【问题讨论】:

    标签: android json parsing kotlin moshi


    【解决方案1】:

    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)
    

    还有你的 moshi 多态适配器:

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

    提供后备始终是一种好习惯,因此您的反序列化不会失败,以防 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()
    

    【讨论】:

      猜你喜欢
      • 2015-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 2014-06-21
      • 2011-06-26
      相关资源
      最近更新 更多