Avatar ·

How to use TypeToken with generics in Gson in Kotlin (solving com.google.gson.internal.LinkedTreeMap error)

Hi everyone! I've been struggling for several days with the problem of JSON deserialization in Kotlin when using generics. I have a function that takes a class type and returns a parsed object. In Java, I would write something like `new TypeToken>(){}.getType()`, but in Kotlin this doesn't work due to erased generics. Here's a simplified example: ```kotlin data class User(val name: String, val age: Int) fun parseList(json: String, clazz: Class): List { val type = TypeToken.getParameterized(List::class.java, clazz).type return Gson().fromJson(json, type) } // Usage val json = """[{"name":"John","age":30}]""" val users = parseList(json, User::class.java) println(users[0].name) // Error: java.lang.ClassCastException: com.google.gson.internal.Linke