Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 缺少带有多晶型适配器工厂的标签_Android_Json_Parsing_Kotlin_Moshi - Fatal编程技术网

Android 缺少带有多晶型适配器工厂的标签

Android 缺少带有多晶型适配器工厂的标签,android,json,parsing,kotlin,moshi,Android,Json,Parsing,Kotlin,Moshi,我试图使用PolymorphicJsonAdapterFactory来获得不同的类型,但总是会遇到奇怪的异常: 测试类型缺少标签 我的实体: @JsonClass(generateAdapter = true) data class TestResult( @Json(name = "test_type") val testType: TestType, ... @Json(name = "session") val session

我试图使用
PolymorphicJsonAdapterFactory
来获得不同的类型,但总是会遇到奇怪的异常:

测试类型缺少标签

我的实体:

@JsonClass(generateAdapter = true)
data class TestResult(
    @Json(name = "test_type") val testType: TestType,
    ...
    @Json(name = "session") val session: Session,
    ...
)
这是我的摩西工厂:

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",
      ...
   ]
}

测试类型必须是会话类的字段

如果测试类型不能在会话类中,则必须为包含特定会话类的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()
提供回退总是一个好的做法,这样在测试类型未知的情况下,反序列化不会失败:

@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()