android - 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
}
但它不起作用。我能怎么做?
解决方案
对于您的 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
推荐阅读
- javascript - 如何防止 React-Bootstrap 汉堡菜单在展开时影响我的其他徽标和图标的位置?
- git - 如何在 Git 中查看不同分支的文件(没有更改)?
- applescript - 根据applescript函数的输出设置变量
- python - Python opencv检测具有交叉点的形状
- azure - 有没有办法通过策略阻止将用户添加到 Azure 资源?
- python - 为什么 nc 文件中的 lat 和 lon 维度会因组装两个 nc 文件而改变?
- java - Univocity Parser - 如何在解析的 bean 中获取行号
- ios - 使用安全的 UITextField 输入密码时,键盘显示延迟较长
- swift - 如何在 SwiftUI 中使用 Swift 手动倒带、停止和转发 Gif
- php - Woocommerce 弱密码复选框(店面子主题)