简体   繁体   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. 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. This type may be a standard Kotlin type (such as Boolean , String , etc), one of my application's types (say, User ) or a generic type (such as HashMap<Int, Boolean> ).此类型可能是标准 Kotlin 类型(例如BooleanString等)、我的应用程序类型之一(例如User )或泛型类型(例如HashMap<Int, Boolean> )。

A very simplified version of this function would be as follows:这个 function 的一个非常简化的版本如下:

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

I'd like to call it passing it the string , and the type I expect to get back from deserializing it, this way:我想称它为传递字符串,以及我希望从反序列化它得到的类型,这样:

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

I've tried using inline and reified , KType , and etc, but I'm still stuck as I'm not experienced with Kotlin's type system and reflection API.我尝试过使用inlinereifiedKType等,但我仍然卡住了,因为我对 Kotlin 的类型系统和反射 API 没有经验。

What is the type of the parameter that would allow me to write and call this function this way?允许我以这种方式编写和调用此 function 的参数类型是什么?

You can use these inline function:您可以使用这些内联 function:

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

And next:接下来:

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

Also you can use these:你也可以使用这些:

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