hfhbd

    hfhbd

    4 months ago
    Hey, I wan to use a custom annotation class during encoding. So I marked my annotation class with @SerialInfo and I use
    descriptor.getElementAnnotations(index)
    , but the annotation for this property is not found. Did I miss something?
    @ExperimentalSerializationApi
    internal fun SerialDescriptor.fixedLengthElement(index: Int) =
        getElementAnnotations(index).filterIsInstance<FixedLength>().singleOrNull()
            ?: error("$serialName not annotated with @FixedLength")
    
    @ExperimentalSerializationApi
    @SerialInfo
    public annotation class FixedLength(val length: Int)
    
    // usage
    override fun <T> encodeSerializableElement(
            descriptor: SerialDescriptor,
            index: Int,
            serializer: SerializationStrategy<T>,
            value: T
        ) {
            serializer.serialize(
                FixedLengthPrimitiveEncoder(
                    serializersModule,
                    descriptor.fixedLengthElement(index).length,
                    builder
                ), value
            )
        }
    
    @Serializable
        data class Sample(
            @FixedLength(10) val date: Instant
        )