繁体   English   中英

Kotlin:传递 Gson 使用的类型

[英]Kotlin: passing a type to be used by Gson

I want to write a function that deserializes a certain JSON String into an object of a certain type using Gson, and returns that object. 此类型可能是标准 Kotlin 类型(例如BooleanString等)、我的应用程序类型之一(例如User )或泛型类型(例如HashMap<Int, Boolean> )。

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

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

我想称它为传递字符串,以及我希望从反序列化它得到的类型,这样:

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

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

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

您可以使用这些内联 function:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM