This question already has answers here:
How to use TypeToken + generics with Gson in Kotlin

(7个答案)


2个月前关闭。




我有JSON字符串如下
var purchases = "[{\"contentId\":\"861723b2-78e4-42ea-8479-40fa0850c314\",\"purchaseType\":\"RENT\"},{\"contentId\":\"138bc762-b539-4749-8706-de2f0eea4b61\",\"purchaseType\":\"PURCHASE\"}]"
我正在尝试将其转换为数据类对象列表
val userPurchases: List<UserPurchases> = Gson().fromJson(purchases,List<UserPurchases>)
这是我的数据类
data class UserPurchases(
    val contentId: String,
    val purchaseType: String)

最佳答案

由下面解决

val purchase: List<UserPurchases> = GsonBuilder().create().fromJson(userPurchases, Array<UserPurchases>::class.java).toList()

07-27 18:39