如何在 Kotlin 中将 TypeToken + 泛型与 Gson 一起使用 [英] How to use TypeToken + generics with Gson in Kotlin

查看:92
本文介绍了如何在 Kotlin 中将 TypeToken + 泛型与 Gson 一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法从自定义类 (Turns) 中获取泛型列表:

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)

它说:

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

推荐答案

创造这个内联乐趣:

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>>()

这篇关于如何在 Kotlin 中将 TypeToken + 泛型与 Gson 一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆