LatLngSerializer.kt consists of custom KSerializer implementation for LatLng class. Example of this KSerializer is shown in HomeAddress.kt.
Last active
May 28, 2023 13:57
-
-
Save tahakorkem/fafe73ce9320b98edd9e59f00130ae3a to your computer and use it in GitHub Desktop.
KotlinX Serialization custom serializer for LatLng
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Serializable | |
@Parcelize | |
data class HomeAddress( | |
val address: String, | |
@Serializable(with = LatLngSerializer::class) // this line is required for custom serialization | |
val location: LatLng, | |
) : Parcelable |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment