【问题标题】:Kotlin: passing a type to be used by GsonKotlin:传递 Gson 使用的类型
【发布时间】:2020-04-11 16:06:04
【问题描述】:

我想编写一个函数,使用 Gson 将某个 JSON String 反序列化为某个类型的对象,并返回该对象。 此类型可能是标准 Kotlin 类型(例如 BooleanString 等)、我的应用程序类型之一(例如 User)或泛型类型(例如 HashMap<Int, Boolean>)。

这个函数的一个非常简化的版本如下:

fun <T> get(jsonString: String, typeOfObj: /*type goes here. T???, typeOf???, etc*/): T? {
    return gson?.fromJson(jsonString, typeOfObj)
}

我想将它传递给 stringtype 我希望通过这种方式从反序列化中返回:

val result: HashMap<Int, Boolean> = get(myString, Map<Int, Boolean>)

我尝试过使用 inlinereifiedKType 等,但我仍然卡住了,因为我对 Kotlin 的类型系统和反射 API 没有经验。

允许我以这种方式编写和调用此函数的参数类型是什么?

【问题讨论】:

    标签: generics kotlin gson


    【解决方案1】:

    你可以使用这些内联函数:

    inline fun <reified T> fromJson(json: String): T {
    return Gson().fromJson(json, object: TypeToken<T>(){}.type)
    }
    

    接下来:

    val result = Gson().fromJson<Result>(pref.result)
    

    你也可以使用这些:

    val turnsType = object : TypeToken<List<Turns>>() {}.type
    val turns = Gson().fromJson<List<Turns>>(pref.turns, turnsType)
    

    【讨论】:

    • 我可以发誓我已经尝试过了,但没有成功……但现在可以了,哈哈!谢谢你,我会接受你的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 1970-01-01
    • 2017-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多