以这种方式设计数据不是一个好习惯,但是如果您无法控制后端,这里有一个如何反序列化的示例
class MyDeserializer : JsonDeserializer<MyAction>{
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): MyAction {
val myAction = MyAction()
val action = json.asJsonObject.get("action")
val data = json.asJsonObject.get("data")
myAction.action = context.deserialize<String>(action, String::class.java)
val myMap = mutableMapOf<String, Any>()
data.asJsonObject.keySet().forEach {
when (it) {
is String -> { myMap[it] = context.deserialize(data.asJsonObject.get(it), String::class.java) }
is MyCustomObject1 -> { myMap[it] = context.deserialize(data.asJsonObject.get(it), MyCustomObject1::class.java) }
is MyCustomObject2 -> { myMap[it] = context.deserialize(data.asJsonObject.get(it), MyCustomObject2::class.java) }
else -> myMap[it] = context.deserialize(data.asJsonObject.get(it), Any::class.java)
}
}
myAction.data = myMap
return myAction
}
}
不要忘记注册你的反序列化器
fun getSmartGson() = GsonBuilder().registerTypeAdapter(MyAction::class.java, MyDeserializer())