Search code examples
kotlinktorkotlinx.serializationarrow-kt

Parsing NonEmptyList directly from JSON


Given this JSON: [{"name": "test"}]. Is there a way I can parse this JSON array directly into an Arrow NonEmptyList?

My background is Scala and I'm exploring Ktor + Arrow. I have an endpoint I'd like to do something like: call.receive<NonEmptyList<DataClass>>(). It seems though since serialization is based on an annotation, without a data class with @Serializable it looks like it does not know how to parse the JSON even with @file:UseSerializers(NonEmptyListSerializer::class) on the file.


Solution

  • After some investigation, with the help of @nomisRev pointers, when using Ktor and installing the JSON serializer, this is what I've arrived at:

    install(ContentNegotiation) {
        json(Json {
            serializersModule =
                SerializersModule { contextual(NonEmptyList::class) { args -> NonEmptyListSerializer(args[0]) } }
        })
    }
    

    https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/serializers.md#contextual-serialization-and-generic-classes

    This is being addressed in Arrow: https://github.com/arrow-kt/arrow/pull/3413