GSON,用于多个类的自定义解串器

时间:2019-03-19 08:58:04

标签: android kotlin gson retrofit2 json-deserialization

我需要为kotlin中的Android应用程序实现自定义GSON解串器(带有Retrofit2)。这是api如何给我结果的示例:

example1:

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

example2:

{
     "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
}

但是它不起作用。我该怎么办?

1 个答案:

答案 0 :(得分:-2)

对于您的JSON响应

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

数据模型类可以是 某些数据

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
)

这些类可以组合以解析整个响应 通用响应

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