I'm having hard time trying to make a generic dese...
# javascript
m
I'm having hard time trying to make a generic deserializing work.
Copy code
private suspend inline fun <reified T> fetch(
    url: String,
    state: ObservableValue<Collection<T>>
) {
    val response1 = client.get(url).body<List<T>>(typeInfo<List<T>>())
    val response2 : List<T> = client.get(url).body()
    val type = typeOf<T>()
}
neither response1, nor response2 is able to properly derive the generic type, even though it's reified.
TypeInfo(type=class List, reifiedType=[object Object], kotlinType=null)
And calling typeOf fails with a weird " This marker function should never been called. Looks like compiler did not eliminate it properly. Please, report an issue if you caught this exception." When the type is provided directly, everything works fine, obviously (
kotlinType
is properly defined). Is that not possible at all, even with reified type? Can I create a
KType
for
List<T>
? Kotlin 1.6.10
a
Can you share more details? Like a full code snippet that fails.
m
The snippet I have here uses ktor client and some backend urls so that would be hard, but I guess the same thing should fail with just kotlinx serialisation. I'll prepare sth like that.
OK, so pure kotlinx serialization works fine
Copy code
fun test() {
    val projects = listOf(Project(1, "A"), Project(2, "B"))
    val encodedProjects = Json.encodeToString(projects)
    val decodedProjects : List<Project> = deserializeGeneric(encodedProjects)
    println(decodedProjects)
}

private inline fun <reified T> deserializeGeneric(encodedStuff: String) =
    Json.decodeFromString<T>(encodedStuff)
But similar ktor doesn't
Copy code
fetch<List<Project>>()

private inline fun <reified T> fetch() {
    val client = HttpClient(Js) {
        install(ContentNegotiation) { json(Json { ignoreUnknownKeys = true }) }
    }

    AppScope.launch {
        val response: T = client.get("$baseUrl/admin/project").body()
        println(response)
    }
}
JsonDecodingException Expected class JsonObject as the serialized body of kotlinx.serialization.Polymorphic<List>, but had class JsonArray
should I search around ktor rather than kotlin js then?
a
should I search around ktor rather than kotlin js then?
I guess so. But I’ll try to reproduce anyway.
🙏 1
m
then I'll wait for your results before reposting on ktor. thank you!
a
Ok I got time. And verified the basic setup JVM Server + JS Client. It seems working well for me. Can you check? https://github.com/antohaby/kotlin-jvm-js-sample Open in IDEA. then run JVM Server by running
main
function. • And then run gradle task:
./gradlew jsNodeRun
205 Views