Skip to content

Instantly share code, notes, and snippets.

@FluxCapacitor2
Created July 11, 2022 21:08
Show Gist options
  • Save FluxCapacitor2/74dbd63f14a5727558f694bef63513eb to your computer and use it in GitHub Desktop.
Save FluxCapacitor2/74dbd63f14a5727558f694bef63513eb to your computer and use it in GitHub Desktop.
A serializer for kotlinx.serialization and KMongo that can accept either an int32 or a double and returns a double.
/**
* A serializer for kotlinx.serialization and KMongo that can accept either an int32 or a double and returns a double.
* Depends on KMongo or another MongoDB library that uses [kbson](https://github.com/jershell/kbson), because
* its FlexibleDecoder gives a hint of what the type is before the value is decoded.
* @author FluxCapacitor2
*/
object LenientDoubleArraySerializer : KSerializer<Array<Double>> {
val s = ListSerializer(LenientDoubleSerializer)
override val descriptor: SerialDescriptor
get() = SerialDescriptor("custom.DoubleArray", s.descriptor)
override fun deserialize(decoder: Decoder): Array<Double> {
return s.deserialize(decoder).toTypedArray()
}
override fun serialize(encoder: Encoder, value: Array<Double>) {
s.serialize(encoder, value.toList())
}
}
object LenientDoubleSerializer : KSerializer<Double> {
override val descriptor: SerialDescriptor
get() = PrimitiveSerialDescriptor("custom.Double", PrimitiveKind.DOUBLE)
override fun deserialize(decoder: Decoder): Double {
decoder as FlexibleDecoder
return when(decoder.reader.currentBsonType) {
BsonType.INT32 -> decoder.reader.readInt32().toDouble()
BsonType.DOUBLE -> decoder.reader.readDouble()
else -> throw SerializationException("Invalid BSON type: ${decoder.reader.currentBsonType}")
}
}
override fun serialize(encoder: Encoder, value: Double) {
encoder.encodeDouble(value)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment