Kotlinx.serialization: Making my own DoubleArray serializer due to primitive arrays shortcoming

Created on 1 Feb 2019  路  2Comments  路  Source: Kotlin/kotlinx.serialization

Is it possible to provide the framework with a DoubleArray serializer that would be used whenever a DoubleArray is encountered in any Serializable class?

DoubleArray and the like are not serializable yet.
From https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/custom_serializers.md it is clear that I could make a serializer for Foo:

@Serializable
class Foo {
  val bar: DoubleArray = DoubleArray(3)
}

However, I would like to just make one serializer for DoubleArray because it is used in many large classes.

If this is not possible I will convert them to ArrayList, but I would rather not.

question

Most helpful comment

Hello,

You could do something like this:

@Serializable
class Foo(
    @Serializable(DoubleArraySerializer::class) val bar: DoubleArray
)

object DoubleArraySerializer : KSerializer<DoubleArray> {

    override val descriptor = ArrayListClassDesc(DoubleDescriptor)

    override fun serialize(encoder: Encoder, obj: DoubleArray) {
        encoder.encodeSerializableValue(ArrayListSerializer(DoubleSerializer), obj.asList())
    }

    override fun deserialize(decoder: Decoder): DoubleArray {
        val doubles = decoder.decodeSerializableValue(ArrayListSerializer(DoubleSerializer))

        return DoubleArray(doubles.size).apply {
            doubles.forEachIndexed { index, double -> this[index] = double }
        }
    }
}

All 2 comments

Hello,

You could do something like this:

@Serializable
class Foo(
    @Serializable(DoubleArraySerializer::class) val bar: DoubleArray
)

object DoubleArraySerializer : KSerializer<DoubleArray> {

    override val descriptor = ArrayListClassDesc(DoubleDescriptor)

    override fun serialize(encoder: Encoder, obj: DoubleArray) {
        encoder.encodeSerializableValue(ArrayListSerializer(DoubleSerializer), obj.asList())
    }

    override fun deserialize(decoder: Decoder): DoubleArray {
        val doubles = decoder.decodeSerializableValue(ArrayListSerializer(DoubleSerializer))

        return DoubleArray(doubles.size).apply {
            doubles.forEachIndexed { index, double -> this[index] = double }
        }
    }
}

Thanks @q-litzler That's close to perfect.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ersin-ertan picture ersin-ertan  路  3Comments

Chris-Corea picture Chris-Corea  路  3Comments

just-kip picture just-kip  路  3Comments

Egorand picture Egorand  路  3Comments

elizarov picture elizarov  路  3Comments