# Using kotlinx.serialization in generic function?

**URL:** <https://discuss.kotlinlang.org/t/using-kotlinx-serialization-in-generic-function/11694>\
**Category:** JavaScript\
**Created:** [February 21, 2019, 11:01pm UTC](https://discuss.kotlinlang.org/t/using-kotlinx-serialization-in-generic-function/11694 "2019-02-21T23:01:37Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![ccfnz](https://avatars.discourse-cdn.com/v4/letter/c/dec6dc/32.png) [@ccfnz](https://discuss.kotlinlang.org/u/ccfnz)\
**Post date:** [February 21, 2019, 11:01pm UTC](https://discuss.kotlinlang.org/t/using-kotlinx-serialization-in-generic-function/11694/1 "2019-02-21T23:01:37Z")

</div>

Hi,

I am trying out the new kotlinx.serialization (in kotlin.js for now) and serializing by json

How would I create a generic find function that returns a correctly typed Kotlin object?

One of my many attempts is below. Here the compiler warns that Serializable is a final type, and also doesn’t know about the serializer method. Also did not have much luck installing the JsonFeature.

Any help on how to do this in a generic way would be appreciated.

```
suspend inline fun <reified T : Serializable> find2(id: Long): T? {
    HttpClient(Js) {
// install(JsonFeature) {
// serializer = GsonSerializer()
// serializer = defaultSerializer()
// }
    }.use {
        // .use automatically closes the client
        val json = it.get<String>("$baseUrl/$id")
        // val ob = kotlinx.serialization.json.Json.parse(Event.serializer(), json)
                                                   // ^^^ Explicit type works (without the Serializable type in the function definition)
        return kotlinx.serialization.json.Json.parse((T.serializer(), json)
                                                   // ^^^ What should I use here??
    }
}

```

---

<div class="post-metadata">

**Author:** ![ccfnz](https://avatars.discourse-cdn.com/v4/letter/c/dec6dc/32.png) [@ccfnz](https://discuss.kotlinlang.org/u/ccfnz)\
**Post date:** [February 22, 2019, 3:23am UTC](https://discuss.kotlinlang.org/t/using-kotlinx-serialization-in-generic-function/11694/2 "2019-02-22T03:23:19Z")

</div>

OK, the problem with the JsonFeature was a version incompatibility between the ktor client and, I guess, the serialization library.

Moving to the later version of ktor allowed the JsonFeature to work.

This then allowed this code to work:

```
suspend inline fun <reified T> find3(id: Long): T? {
    HttpClient(Js) {
        install(JsonFeature) {
            // serializer = GsonSerializer()
            serializer = defaultSerializer()
        }
    }.use {
        // .use automatically closes the client
        return it.get<T>("$baseUrl/$id")
    }
}

```

I would still be keen to know how the function should be defined if I was to read the json myself and then try and parse it (i.e. the original question), however the original problem is solved by the above.
