Ktor: KotlinxSerializer unable to parse lists

Created on 29 Jan 2019  路  8Comments  路  Source: ktorio/ktor

Ktor Version

1.1.2

Ktor Engine Used(client or server and name)

iOS Client

JVM Version, Operating System and Relevant Context

iOS 12

Feedback

Hey, the KotlinxSerializer is apparently unable to deserialized JSON payloads having lists at the root.
For instance, a JSON payload like the following:

[{"foo": "bar1"}, {"foo": "bar2}]

would not be deserialized correctly.

After some trial and error, the problem lies on KotlinSerializer.kt:94:

    private fun lookupSerializerByType(type: KClass<*>): KSerializer<*> {
        mappers[type]?.let { return it } // <--
        return (type.defaultSerializer() ?: type.serializer())
    }

From what I understand, no mapper will be found because type would be kotlin.collections.List. Is that correct?

Thank you in advance :)

documentation serialization

Most helpful comment

Thanks, tried it but still got same result.

All 8 comments

Hi @viteinfinite, thanks for the report.

Did you try registerList to register top-level list serializers?

registerList() is not working for me. ktor deserializes single Todo fine, but for list throws: Can't locate argument-less serializer for class kotlin.collections.List. For generic classes, such as lists, please provide serializer explicitly.

    val httpClient = HttpClient() {
        install(JsonFeature) {
            serializer = KotlinxSerializer().apply {
                registerList(Todo.serializer().list)
            }
        }
    }

    suspend fun getTodo(): Todo = coroutineScope {
        val urlString = "https://jsonplaceholder.typicode.com/todos/1"
        httpClient.get<Todo> {
            url(urlString)
        }
    }

    suspend fun getTodos(): List<Todo> = coroutineScope {
        val urlString = "https://jsonplaceholder.typicode.com/todos"
        httpClient.get<List<Todo>> {
            url(urlString)
        }
    }

Could you try registerList(Todo.serializer()) instead?

Thanks, tried it but still got same result.

Are there any advancements? (

The fix should be available from kotlin 1.3.50

Parsing lists is already working in ktor version 1.3.0 (currently beta). In this new version there is no need to register the serializers.

Fixed with typeOf support in 1.3.0

Was this page helpful?
0 / 5 - 0 ratings