[英]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 類型(例如Boolean
、 String
等)、我的應用程序類型之一(例如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>)
我嘗試過使用inline
和reified
、 KType
等,但我仍然卡住了,因為我對 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.