bernardo.g
bernardo.g

Reputation: 758

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?

Upvotes: 1

Views: 755

Answers (1)

Andres Rivas
Andres Rivas

Reputation: 162

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)

Upvotes: 1

Related Questions