typetoken

How to use TypeToken + generics with Gson in Kotlin

我们两清 提交于 2019-11-27 03:09:05
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' Create this inline fun: inline fun <reified T> Gson.fromJson(json: String) = this.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) NOTE : This approach was not possible before in old kotlin plugin versions but now you

How to use TypeToken + generics with Gson in Kotlin

橙三吉。 提交于 2019-11-26 10:21:33
问题 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\' 回答1: Create this inline fun: inline fun <reified T> Gson.fromJson(json: String) = this.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 =