且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Kotlin 中将 TypeToken + 泛型与 Gson 一起使用

更新时间:2023-01-16 23:39:31

创造这个内联乐趣:

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)

以前的替代方案:

备选方案 1:

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

你必须把 object : 和特定类型放在 fromJson>

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

备选方案 2:

正如@cypressious 提到的,它也可以通过这种方式实现:

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

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

用作:

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