如何在Kotlin中使用gson反序列化到ArrayList [英] How to use gson deserialize to ArrayList in Kotlin

查看:752
本文介绍了如何在Kotlin中使用gson反序列化到ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用此类存储数据

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

并在ArrayList中使用它

And use it in 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

But this method will give me LinkedTreeMap, not Item, I cannot cast LinkedTreeMap to Item

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

What is correct way to deserialize to json in Kotlin?

推荐答案

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

Try this code for deserialize list

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

这篇关于如何在Kotlin中使用gson反序列化到ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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