d

    dimitar_

    1 year ago
    Hey, I'm trying to serialize an object, that has an array of LongRange objects - but with no luck. I have a custom serializer for the LongRange objects
    object LongRangeSerializer: KSerializer<LongRange> {
        override val descriptor = buildClassSerialDescriptor("LongRange") {
            element<Long>("first")
            element<Long>("last")
        }
    
        override fun deserialize(decoder: Decoder): LongRange {
            var first = 0L
            var last = 0L
    
            decoder.decodeStructure(descriptor) {
                first = decodeLongElement(descriptor, 0)
                last = decodeLongElement(descriptor, 1)
            }
    
            return first..last
        }
    
        override fun serialize(encoder: Encoder, value: LongRange) {
            encoder.encodeStructure(descriptor) {
                encodeLongElement(descriptor, 0, value.first)
                encodeLongElement(descriptor, 1, value.last)
            }
        }
    }
    And I tried:
    @Serializable class Container(@Serializable(with = LongRangeSerializer::class) val ranges: Array<LongRange>)
    with no luck. Can't seem to find any pointers anywhere. Tried using a List also, tried also with
    @Contextual
    - same issue. The error is:
    Kotlin: Serializer has not been found for type 'LongRange'. To use context serializer as fallback, explicitly annotate type or property with @Contextual
    d

    diesieben07

    1 year ago
    The property is of type
    Array<LongRange>
    so you need to give it a serializer for arrays, not
    LongRange
    . In this case
    ArraySerializer
    . However that is a top level function, so not sure how to use it with
    Serializable(with = )
    d

    dimitar_

    1 year ago
    Tried something with a custom serializer for Array<LongRange>... but it's the same. The weird thing is that even if I annotate the field with
    @Contextual
    the compiler gives the same error.
    Hah! Found a solution 😄
    @file:UseSerializers(LongRangeSerializer::class)
    at the beginning of the file seems to "remove" the compiler error 🙂
    e

    ephemient

    1 year ago
    I would have expected
    val ranges: Array<@Serializable(with = LongRangeSerializer::class) LongRange>
    to work
    but
    @file:UseSerializers
    is fine
    d

    dimitar_

    1 year ago
    @ephemient thanks! I didn't know you can declare it like that 🙂 I actually prefer your way.