kur*_*urt 5 javascript dynamic kotlin kotlin-js-interop
例如,我们有这样的结构:
data class Item(
val city: String,
val name: String
)
val structure = mapOf("items" to listOf(
Item("NY", "Bill"),
Item("Test", "Test2"))
)
Run Code Online (Sandbox Code Playgroud)
我想在 Javascript 中获取这个对象:
var structure = {
"items": [
{
"city": "NY",
"name": "Bill"
},
{
"city": "Test",
"name": "Test2"
}
]
}
Run Code Online (Sandbox Code Playgroud)
我们如何map从 Kotlin 转换为dynamicJavascript 中具有这种结构的类型?
我只找到这种明确的方式:
fun Map<String, Any>.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<Any>).toJs()
else -> throw RuntimeException("value has invalid type")
}
}
return result
}
fun List<Any>.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
}
Run Code Online (Sandbox Code Playgroud)
我知道也可以通过序列化/反序列化来做到这一点,但我认为它会更慢并且有一些开销。
有谁知道将 Kotlin 转换object为纯 Javascript object(dynamicKotlin 类型)的简单方法?
您可以使用这个简单的函数来做到这一点
inline fun <I> objectOf(
jsonObject: I = js("new Object()").unsafeCast<I>(),
writer: I.() -> Unit
): I {
writer(jsonObject)
return jsonObject
}
Run Code Online (Sandbox Code Playgroud)
用法:
interface Structure {
var items: Array<Item>
interface Item {
var city: String
var name: String
}
}
fun main() {
val structure0 = objectOf<dynamic> {
items = arrayOf<dynamic>(
objectOf {
city = "NY"
name = "Bill"
orAnything = "Literly, anything!"
},
objectOf { city = "Test"; name = "Test2" }
)
}
println(JSON.stringify(structure0))
// {"items":[{"city":"NY","name":"Bill","orAnything":"Literly, anything!"},{"city":"Test","name":"Test2"}]}
val structure1 = objectOf<Structure> {
items = arrayOf(
objectOf {
city = "NY"
name = "Bill"
// orAnything = "Literly anything" // Compile time Error: Unresolved reference: orAnything
},
objectOf {
city = "Test"
name = "Test2"
}
)
}
println(JSON.stringify(structure1))
// {"items":[{"city":"NY","name":"Bill"},{"city":"Test","name":"Test2"}]}
val structure2 = objectOf(structure1) {
items.forEach {
it.city = "Khartoum"
}
}
println(JSON.stringify(structure2))
// {"items":[{"city":"Khartoum","name":"Bill"},{"city":"Khartoum","name":"Test2"}]}
val structure3 = objectOf(structure0) {
items.unsafeCast<Array<dynamic>>().forEach {
it.name = "Shalaga44"
}
}
println(JSON.stringify(structure3))
//{"items":[{"city":"NY","name":"Shalaga44","orAnything":"Literly, anything!"},{"city":"Test","name":"Shalaga44"}]}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1957 次 |
| 最近记录: |