2

由于 MutableMap 对象,我无法使用 Gson 将 JSON 转换为 Kotlin 数据类。数据类

data class MyAction(
    @Key("action") var action: String = "default",
    @Key("data") var data: MutableMap<String, Any> = mutableMapOf()
)

地图中的值data有几种类型。我尝试过使用 TypeToken 和泛型,就像在这里一样,但没有用。接收到的json示例:

  1. {"action":"playVideo","data":{"media":{"id":15060328,"url":" http://url_to_get_item ","name":"item name","shortDescription": “短描述”}

  2. {"action":"setSpeed","data":{"value":1}}

  3. {"action":"getProperty","data":{"value":"position"}}

4

1 回答 1

1

以这种方式设计数据不是一个好习惯,但是如果您无法控制后端,这里有一个如何反序列化的示例

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())
于 2019-05-21T15:07:01.513 回答