Matthew Cachia

    Matthew Cachia

    1 year ago
    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.
    // 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!
    Dominaezzz

    Dominaezzz

    1 year ago
    Hmm, probably want to register a contextual or file level serializer.
    e

    ephemient

    1 year ago
    you could manually specify the serializer:
    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
    Json {
        serializersModule = SerializersModule {
            contextual(Either::class) { (lSerializer, rSerializer) ->
                EitherSerializer(lSerializer, rSerializer)
            }
        }
    }
        .decodeFromString<Either<SchemaObject, ReferenceObject>>(json)