Skip to content

Instantly share code, notes, and snippets.

@tahakorkem
Last active May 28, 2023 13:57
Show Gist options
  • Save tahakorkem/fafe73ce9320b98edd9e59f00130ae3a to your computer and use it in GitHub Desktop.
Save tahakorkem/fafe73ce9320b98edd9e59f00130ae3a to your computer and use it in GitHub Desktop.
KotlinX Serialization custom serializer for LatLng
class LatLngSerializer : KSerializer<LatLng> {
override val descriptor: SerialDescriptor = buildClassSerialDescriptor("LatLng") {
element<Double>("latitude")
element<Double>("longitude")
}
override fun serialize(encoder: Encoder, value: LatLng) {
encoder.encodeStructure(descriptor) {
encodeDoubleElement(descriptor, 0, value.latitude)
encodeDoubleElement(descriptor, 1, value.longitude)
}
}
override fun deserialize(decoder: Decoder): LatLng {
return decoder.decodeStructure(descriptor) {
var latitude = 0.0
var longitude = 0.0
loop@ while (true) {
when (val index = decodeElementIndex(descriptor)) {
0 -> latitude = decodeDoubleElement(descriptor, 0)
1 -> longitude = decodeDoubleElement(descriptor, 1)
CompositeDecoder.DECODE_DONE -> break@loop
else -> error("Unexpected index: $index")
}
}
LatLng(latitude, longitude)
}
}
}
@Serializable
@Parcelize
data class HomeAddress(
val address: String,
@Serializable(with = LatLngSerializer::class) // this line is required for custom serialization
val location: LatLng,
) : Parcelable

LatLngSerializer.kt consists of custom KSerializer implementation for LatLng class. Example of this KSerializer is shown in HomeAddress.kt.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment