How to use gson deserialize to ArrayList in Kotlin

微笑、不失礼 提交于 2020-06-07 06:26:05

问题


I use this class to store data

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

And use it in ArrayList

public var itemList = ArrayList<Item>()

Use this code to serialize the object

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

And deserialize

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

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

What is correct way to deserialize to json in Kotlin?


回答1:


Try this code for deserialize list

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



回答2:


In my code I just use:

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

I give here a complet example.

First the type and the list array:

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

The main code:

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

The exit:

***OK***


来源:https://stackoverflow.com/questions/51376954/how-to-use-gson-deserialize-to-arraylist-in-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!