将Kotlin / Js对象动态转换为纯javascript对象的简单方法是什么?
例如,我们有这样的结构:
data class Item( val city: String, val name: String ) val structure = mapOf("items" to listOf( Item("NY", "Bill"), Item("Test", "Test2")) )
我想用Javascript获取这个对象:
var structure = { "items": [ { "city": "NY", "name": "Bill" }, { "city": "Test", "name": "Test2" } ] }
如何我们可以将map
从Kotlin转换为dynamic
types的Javascript结构?
我只find这个明确的方法:
fun Map.toJs(): dynamic { val result: dynamic = object {} for ((key, value) in this) { when (value) { is String -> result[key] = value is List -> result[key] = (value as List).toJs() else -> throw RuntimeException("value has invalid type") } } return result } fun List.toJs(): dynamic { val result: dynamic = js("[]") for (value in this) { when (value) { is String -> result.push(value) is Item -> result.push(value.toJs()) else -> throw RuntimeException("value has invalid type") } } return result } fun Item.toJs(): dynamic { val result: dynamic = object {} result["city"] = this.city result["name"] = this.name return result }
我知道这也可以做到这一点序列化/反序列化 ,但我认为这将是较慢,并有一定的开销。
有谁知道简单的方法来隐藏Kotlin object
为纯JavaScript object
( dynamic
Kotlintypes)?
我可能不会真正理解你的问题,所以请原谅,如果这没有帮助。 就我个人而言,我是使用Klaxon的粉丝: https : //github.com/cbeust/klaxon
您可以编写自己的reflection实用程序来迭代数据类中的所有属性,并将其转换为JSON。