Hey, I'm trying to serialize an object, that has ...
# serialization
d
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
Copy code
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:
Copy code
@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
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
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.
e
I would have expected
Copy code
val ranges: Array<@Serializable(with = LongRangeSerializer::class) LongRange>
to work
but
@file:UseSerializers
is fine
d
@ephemient thanks! I didn't know you can declare it like that 🙂 I actually prefer your way.