Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use TypeToken + generics with Gson in Kotlin

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' 
like image 824
Juan Saravia Avatar asked Oct 28 '15 01:10

Juan Saravia


People also ask

What is TypeToken in Kotlin?

object: is used in Kotlin to instantiate anonymous class instances which extend from the parent class. In other words, this part object: TypeToken(){} actually creates an anonymous class that is a child of TypeToken class.

What is TypeToken GSON?

protected TypeToken() Constructs a new type literal. Derives represented class from type parameter. Clients create an empty anonymous subclass.

Does GSON work with Kotlin?

Gson is a Java/Kotlin library for converting Java/Kotlin Objects into JSON representation, also a JSON string to an equivalent Java/Kotlin object. We have some ways to add Gson library to our Kotlin project.


1 Answers

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>>() 
like image 80
Juan Saravia Avatar answered Sep 21 '22 13:09

Juan Saravia