首页 > 解决方案 > GSON,多个类的自定义反序列化器

问题描述

我需要在 kotlin 中为我的 Android 应用程序实现一个自定义 GSON 反序列化器(使用 Retrofit2)。这是 api 如何给我结果的示例:

示例1:

 {
     "res": {
          "status": {
              "code": 0,
              "message": "some message",
          }
     },
     "somedata": {
         "someid" = "12345",
         "sometext" = "a text" 
     }
 }

示例2:

{
     "res": {
          "status": {
              "code": 0,
              "message": "another message",
          }
     },
     "anotherdata": {
         "anotherid" = "54321",
         "anothertext" = "b text" 
     }
 }

这是用于映射数据的相对 kotlin 类(我将使用反序列化器在“res”对象中提取数据):

abstract class GenericResponse() {
    //abstract class for common fields
    constructor(status: Status?) : this()
}

class Status(
    val code: Int,
    val message: String
)

这是特定的响应类:

data class SomeData(
    val status: Status,
    val someid : String,
    val sometext : String
): GenericResponse(status)


data class AnotherData(
    val status: Status,
    val anotherid : String,
    val anothertext : String
): GenericResponse(status)

我试图创建一个实现 JsonDeserializer 的自定义反序列化器类,例如:

class CustomDeserializer : JsonDeserializer<GenericResponse> {
    override fun deserialize(
        json: JsonElement?,
        typeOfT: Type?,
        context: JsonDeserializationContext?
    ): GenericResponse {

    val rootElement = json!!.asJsonObject.getAsJsonObject("res")
    //further implementation, should return SomeData or AnotherData object
}

但它不起作用。我能怎么做?

标签: androidkotlingsonretrofit2json-deserialization

解决方案


对于您的 JSON 响应

{
"res": {
    "status": {
        "code": 0,
        "message": "some message"
    }
},
"somedata": {
    "someid": "12345",
    "sometext": "a text"
},
"anotherdata": {
    "anotherid": "54321",
    "anothertext": "b text"
}
}

数据模型类可以是 Somedata

data class Somedata(
val someid: String,
val sometext: String
)

地位

data class Status(
val code: Int,
val message: String
)

另一个数据

data class Anotherdata(
val anotherid: String,
val anothertext: String
)

这些类可以组合起来解析整个响应GenericResponse

data class GenericResponse(
val anotherdata: Anotherdata,
val res: Res,
val somedata: Somedata
)

在改造中使用

@POST("url")
fun callingMethod(@Field("username") username: String, @Field("password") 
password: String): GenericResponse

推荐阅读