首页 > 解决方案 > 如何观察 Moshi Kotlin 中的意外响应?

问题描述

当 api 的 JSON 响应发送除 STATIONARYTOOL 或 STATIONARYTOOL 以外的其他工具时,我的应用程序崩溃了,我如何观察 Moshi 中的后端是否发送了一些额外的工具。我尝试使用“.withDefaultValue”,但没有奏效。我应该如何实现它。(注意我没有列出/知道,这样应用程序就不会抛出错误?


val moshi: Moshi = Moshi.Builder()
        .add(PolymorphicAdapters.tool)
.build()

object PolymorphicAdapters {

        val tool: PolymorphicJsonAdapterFactory<Tool> =
            PolymorphicJsonAdapterFactory.of(Tool::class.java, StaticConstants.TYPE)
                .withSubtype(
                    Tool.STATIONARYTOOL::class.java,
                    Tool.STATIONARYTOOL.name
                )

}

sealed class Tool(
    @Json(name = StaticConstants.TYPE) val type: Tooltype,
    var position: Long = 0
) {

    @JsonClass(generateAdapter = true)
    data class STATIONARYTOOL(
        val `data`: List<GenericDataCard.StationaryDataCard> = listOf(),
        val style: String = ""
    ) :
        Tool(Tool.STATIONARYTOOL)
    }

标签: androidkotlinpolymorphismretrofitmoshi

解决方案


推荐阅读