简体   繁体   中英

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. 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> ).

A very simplified version of this function would be as follows:

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.

What is the type of the parameter that would allow me to write and call this function this way?

You can use these inline 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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