如何在 Kotlin 中使用 gson 反序列化到 ArrayList

问题描述 投票:0回答:5

我用这个类来存储数据

public class Item(var name:String,
                  var description:String?=null){
}

并在 ArrayList 中使用它

public var itemList = ArrayList<Item>()

使用这段代码序列化对象

val gs=Gson()
val itemListJsonString = gs.toJson(itemList)

反序列化

itemList = gs.fromJson<ArrayList<Item>>(itemListJsonString, ArrayList::class.java)

但是这个方法会给我

LinkedTreeMap
,而不是
Item
,我不能将LinkedTreeMap投射到Item

在 Kotlin 中反序列化为 json 的正确方法是什么?

android kotlin gson
5个回答
79
投票

尝试使用此代码反序列化列表

val gson = Gson()
val itemType = object : TypeToken<List<Item>>() {}.type
itemList = gson.fromJson<List<Item>>(itemListJsonString, itemType)

7
投票

您可以定义一个内联具体化扩展函数,如:

internal inline fun <reified T> Gson.fromJson(json: String) =
    fromJson<T>(json, object : TypeToken<T>() {}.type)

像这样使用它:

val itemList: List<Item> = gson.fromJson(itemListJsonString)

默认情况下,类型在运行时被擦除,因此 Gson 无法知道它必须反序列化哪种

List
。但是,当您将类型声明为
reified
时,您会在运行时保留它。所以现在 Gson 有足够的信息来反序列化
List
(或任何其他通用对象)。


2
投票

在我的代码中,我只使用:

import com.google.gson.Gson
Gson().fromJson(string_var, Array<Item>::class.java).toList() as ArrayList<Type>

我在这里给出一个完整的例子。

首先是类型和列表数组:

class Item(var name:String,
           var description:String?=null)
var itemList = ArrayList<Item>()

主要代码:

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***

2
投票

而不是接受的答案(有效但创建一个对象来获取它的类型),你可以这样做:

val gson = Gson()
itemList = gson.fromJson(itemListJsonString, Array<Item>::class.java)

当面向 JVM 平台时,“Array”表示 Java 数组。这不是 ArrayList,但您可以访问这些项目(通常在解析 JSON 后就需要)。

如果您仍然需要操作列表,您可以通过以下方式轻松地将其转换为可变列表:

itemsList.toMutableList()

0
投票

这可能已经得到解答,但对于 2023 年 4 月的 Kotlin,您可以创建此扩展:

internal inline fun <reified T> Gson.fromJsonList(jsonString: String) =
         object: TypeToken<List<T>>() { }.type

然后您可以按如下方式使用它:

val discountList = Gson().fromJsonList<Discount>(jsonString)

希望这对某人有所帮助:)干杯

© www.soinside.com 2019 - 2024. All rights reserved.