【问题标题】:Moshi and retrofit2: parse content of root elementMoshi和retrofit2:解析根元素的内容
【发布时间】:2020-05-07 10:57:41
【问题描述】:

从今天开始,我收到了类似的 json 回复:

{
   "status" : "Ok",
   "otherField" : "Somevalues" 
}

我映射到像这样的类

data class MyResponse(
    val status : String,
    val otherField : String
)

现在响应结构发生了变化

{
   "rootElement" : {
       "status" : "Ok",
       "otherField" : "Somevalues" 
    }
}

有没有办法告诉 Moshi 直接解析“rootElement”的内容而不改变“MyResponse”结构?

【问题讨论】:

    标签: android json kotlin retrofit2 moshi


    【解决方案1】:

    有没有办法告诉 Moshi 直接解析“rootElement”的内容而不改变“MyResponse”结构?

    如果我正确理解了您的要求,是的,您可以在不更改 MyResponse 数据类的情况下解析 rootElement 的内容。再创建一个 Kotlin 数据类,如下所示

    data class ResponseRoot (
        val rootElement : MyResponse
    )
    

    并为您的改造响应使用此 ResponseRoot 数据类返回类型,而不是 MyResponse 类。

    在您的 API 界面中进行更改

    @GET("url/here/")
    fun fooBar(/* paramters if there any */): Call<ResponseRoot>
    

    【讨论】:

      猜你喜欢
      • 2018-06-20
      • 1970-01-01
      • 2018-08-09
      • 2022-06-23
      • 2020-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多