将数据 class 转换为 kotlin 映射

Transform data class to map kotlin

我的问题是我需要将 kotlin 中的数据 class 转换为地图,因为我需要根据要求使用此结构,因为此响应将用于 groovy classes 并且有一个 post-process,其中有验证迭代等,与此地图。我的数据 class 是下一个(播客):

data class PodCast(val id: String, val type: String, val items: List<Item>, val header: Header, val cellType:String? = "")

data class Item(val type: String, val parentId: String, val parentType: String, val id: String, val action: Action, val isNew: Boolean)

data class Header(val color: String, val label: String)

data class Action(val type: String, val url: String)

我手动进行了转换,但我需要更复杂的方法来完成此任务。

谢谢。

这个我做的很简单。我只使用 .properties groovy 方法获得了对象的属性,该方法将对象作为地图提供给了我。

您也可以使用 Gson 执行此操作,方法是将数据 class 序列化为 json,然后将 json 反序列化为映射。此处显示双向转换:

val gson = Gson()

//convert a data class to a map
fun <T> T.serializeToMap(): Map<String, Any> {
    return convert()
}

//convert a map to a data class
inline fun <reified T> Map<String, Any>.toDataClass(): T {
    return convert()
}

//convert an object of type I to type O
inline fun <I, reified O> I.convert(): O {
    val json = gson.toJson(this)
    return gson.fromJson(json, object : TypeToken<O>() {}.type)
}

查看类似问题here