I have the following `Either<L, R>` construc...
# serialization
m
I have the following
Either<L, R>
construct which is a third party (and therefore created its own serialiser:
EitherSerializer
). However, deserialising straight to it doesn't work. typealias doesn't work either.
Copy code
// yields kotlinx.serialization.SerializationException: Serializer for class 'Either' is not found.
Json.decodeFromString<Either<SchemaObject, ReferenceObject>>(json)


// yields  kotlinx.serialization.SerializationException: Serializer for class 'Either' is not found.
typealias EitherAlias<L, R> = @Serializable(EitherSerializer::class) Either<L, R>
...
Json.decodeFromString<EitherAlias>(json)


// works fine!
@Serializable
data class NestedInAClass(val schema: @Serializable(EitherSerializer::class) Either<SchemaObject, ReferenceObject>)
...
Json.decodeFromString<NestedInAClass>(json)
It looks like it would work only if it is nested within a serialised class. I don't see why typealias wouldn't work. Any help would be appreciated!
d
Hmm, probably want to register a contextual or file level serializer.
e
you could manually specify the serializer:
Copy code
Json.decodeFromString(EitherSerializer(SchemaObject.serializer(), ReferenceObject.serializer()), json)
but yeah, otherwise you need to register the serializer somehow.
@file:UseSerializers
is short-hand for adding it to all declarations within the file, otherwise
Copy code
Json {
    serializersModule = SerializersModule {
        contextual(Either::class) { (lSerializer, rSerializer) ->
            EitherSerializer(lSerializer, rSerializer)
        }
    }
}
    .decodeFromString<Either<SchemaObject, ReferenceObject>>(json)