Kotlin Multiplatform WASM模块调用REST API遇非法转换错误求助
Kotlin/WASM调用REST API解决Illegal Cast错误
问题根源
Kotlin/WASM与JavaScript的类型映射存在差异,直接对fetch返回的Response或其text()/json()的Promise结果进行强转,会触发类型不兼容的非法转换错误。
解决方案
1. 修复文本数据获取(text())
使用dynamic作为中间类型规避类型映射冲突,再安全转换为Kotlin字符串:
import kotlinx.coroutines.await suspend fun fetchApiData(url: String): String { println("Fetching data from $url") // 用dynamic接收fetch结果,避免类型强转冲突 val response = js("fetch(url)").await() as dynamic if (response.ok) { println("Getting data") val data = response.text().await() as String return data } else { throw Exception("Failed to fetch data: ${response.statusText}") } }
2. 处理JSON数据解析
如果API返回JSON,结合kotlinx.serialization做类型安全解析,避免直接操作dynamic:
首先定义序列化数据类:
import kotlinx.serialization.Serializable @Serializable data class YourApiResponse( // 根据API返回结构定义字段,示例: val id: Int, val name: String, val content: String )
然后修改API调用函数:
import kotlinx.coroutines.await import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json import kotlin.js.JSON suspend fun fetchJsonApiData(url: String): YourApiResponse { val response = js("fetch(url)").await() as dynamic if (!response.ok) { throw Exception("Failed to fetch data: ${response.statusText}") } // 先将JSON转为字符串,再用kotlinx.serialization解析 val jsonString = JSON.stringify(response.json().await()) return Json.decodeFromString(jsonString) }
额外注意事项
- 确保项目已添加
kotlinx-coroutines-core及对应WASM依赖 - 使用
kotlinx.serialization时,需在build.gradle.kts中启用序列化插件并添加对应依赖
内容的提问来源于stack exchange,提问作者Basshamut
相关产品推荐
相关产品推荐

