Android 如何在Kotlin中使用gson反序列化ArrayList
我使用这个类来存储数据Android 如何在Kotlin中使用gson反序列化ArrayList,android,kotlin,gson,Android,Kotlin,Gson,我使用这个类来存储数据 public class Item(var name:String, var description:String?=null){ } 并在ArrayList中使用它 public var itemList = ArrayList<Item>() 并反序列化 itemList = gs.fromJson<ArrayList<Item>>(itemListJsonString, ArrayList:
public class Item(var name:String,
var description:String?=null){
}
并在ArrayList中使用它
public var itemList = ArrayList<Item>()
并反序列化
itemList = gs.fromJson<ArrayList<Item>>(itemListJsonString, ArrayList::class.java)
itemList=gs.fromJson(itemListJsonString,ArrayList::class.java)
但此方法将为我提供LinkedTreeMap
,而不是Item
,我无法将LinkedTreeMap强制转换为Item
在Kotlin中反序列化为json的正确方法是什么?请尝试以下代码以获取反序列化列表
val gson = Gson()
val itemType = object : TypeToken<List<Item>>() {}.type
itemList = gson.fromJson<List<Item>>(itemListJsonString, itemType)
val gson=gson()
val itemType=object:TypeToken(){}.type
itemList=gson.fromJson(itemListJsonString,itemType)
在我的代码中,我只使用:
import com.google.gson.Gson
Gson().fromJson(string_var, Array<Item>::class.java).toList() as ArrayList<Type>
您可以定义内联具体化扩展函数,如:
internal inline fun <reified T> Gson.fromJson(json: String) =
fromJson<T>(json, object : TypeToken<T>() {}.type)
内部内联fun Gson.fromJson(json:String)=
fromJson(json,对象:TypeToken(){}.type)
然后像这样使用它:
val itemList: List<Item> = gson.fromJson(itemListJsonString)
val itemList:List=gson.fromJson(itemListJsonString)
默认情况下,类型在运行时被擦除,因此Gson无法知道它必须反序列化哪种类型的
列表。但是,如果将类型声明为具体化
,则会在运行时保留该类型。因此,现在Gson有足够的信息来反序列化列表(或任何其他通用对象)。这真的很有帮助。你能解释一下你的答案吗,比如你是怎么想出第二行的?我是Kotlin(和Java)的新手,我对这个结构不太熟悉。例如,为什么不能让第二个参数类似于.class?如果我们不知道类型项呢。?用JSON来吸引Java、Kotlin。
itemList.add( Item("Ball","round stuff"))
itemList.add(Item("Box","parallelepiped stuff"))
val striJSON = Gson().toJson(itemList) // To JSON
val backList = Gson().fromJson( // Back to another variable
striJSON, Array<Item>::class.java).toList() as ArrayList<Item>
val striJSONBack = Gson().toJson(backList) // To JSON again
if (striJSON==striJSONBack) println("***ok***")
***OK***
internal inline fun <reified T> Gson.fromJson(json: String) =
fromJson<T>(json, object : TypeToken<T>() {}.type)
val itemList: List<Item> = gson.fromJson(itemListJsonString)