代码之家  ›  专栏  ›  技术社区  ›  giozh

GSON,用于多个类的自定义反序列化程序

  •  0
  • giozh  · 技术社区  · 5 年前

    例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)
    

    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
    }
    

    0 回复  |  直到 5 年前
        1
  •  -2
  •   Manoj Perumarath    5 年前

    对于你的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