How to use TypeToken + generics with Gson in Kotlin

Juan Saravia picture Juan Saravia · Oct 28, 2015 · Viewed 45.3k times · Source

I'm unable to get a List of generic type from a custom class (Turns):

val turnsType = TypeToken<List<Turns>>() {}.type
val turns = Gson().fromJson(pref.turns, turnsType)

it said:

cannot access '<init>' it is 'public /*package*/' in 'TypeToken'

Answer

Juan Saravia picture Juan Saravia · Oct 28, 2015

Create this inline fun:

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

and then you can call it in this way:

val turns = Gson().fromJson<Turns>(pref.turns)
// or
val turns: Turns = Gson().fromJson(pref.turns)

Previous Alternatives:

ALTERNATIVE 1:

val turnsType = object : TypeToken<List<Turns>>() {}.type
val turns = Gson().fromJson<List<Turns>>(pref.turns, turnsType)

You have to put object : and the specific type in fromJson<List<Turns>>


ALTERNATIVE 2:

As @cypressious mention it can be achieved also in this way:

inline fun <reified T> genericType() = object: TypeToken<T>() {}.type

use as:

val turnsType = genericType<List<Turns>>()