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

问题描述

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

它表示:

 无法访问'< init>'它是'公开的/ *包* /'in'TypeToken'


解决方案

创建这个内联乐趣:

 内联趣味< reified T> Gson.fromJson(json:String)= this.fromJson< T>(json,object:TypeToken< T>(){} .type)

然后你可以这样调用它:

  val turns = Gson() .fromJson< Turns>(pref.turns)
//或
val turn:Turns = Gson()。fromJson(pref.turns)

注意:这种方法在旧的kotlin插件版本中是不可能的,但现在您可以使用它。






以前的替代品:



替代品1:

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

object:以及 fromJson的具体类型< List< Turns>>






其他选择2:



它也可以通过这种方式实现:

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

p>

  val turnsType = genericType< List< 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)

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 are able to use it.


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

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

09-26 21:06