Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use gson deserialize to ArrayList in Kotlin

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?

like image 285
CL So Avatar asked Jul 17 '18 08:07

CL So


People also ask

How do you deserialize with GSON?

Deserialization in the context of Gson means converting a JSON string to an equivalent Java object. In order to do the deserialization, we need a Gson object and call the function fromJson() and pass two parameters i.e. JSON string and expected java type after parsing is finished. Program output.

What is the difference between GSON and Jackson?

Both Gson and Jackson are good options for serializing/deserializing JSON data, simple to use and well documented. Advantages of Gson: Simplicity of toJson/fromJson in the simple cases. For deserialization, do not need access to the Java entities.


2 Answers

Try this code for deserialize list

val gson = Gson()
val itemType = object : TypeToken<List<Item>>() {}.type
itemList = gson.fromJson<List<Item>>(itemListJsonString, itemType)
like image 161
SergeyBukarev Avatar answered Oct 10 '22 02:10

SergeyBukarev


You can define a inline reified extension function like:

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

And use it like:

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

By default, types are erased at runtime, so Gson cannot know which kind of List it has to deserialize. However, when you declare the type as reified you preserve it at runtime. So now Gson has enough information to deserialize the List (or any other generic Object).

like image 22
David Miguel Avatar answered Oct 10 '22 04:10

David Miguel