I have a class ```@kotlinx.serialization.Serializa...
# serialization
b
I have a class
Copy code
@kotlinx.serialization.Serializable
data class Geolocation(
    val latitude: Double,
    val longitude: Double
)
that I'm using to get responses from rest calls. Unfortunately the rest api is not consistent and so in some places I need to use
lat
and
lng
instead of
latitude
and
longitude
. What is the best way to handle this? A custom serializer or extend the class and add
@SerialName
if that's possible? I'd like to really just have one
Geolocation
so I'm leaning towards the custom serializer...
e
Copy code
@Serializable
data class AbbreviatedGeolocation(
    val lat: Double,
    val lng: Double
)

object AbbreviatedGeolocationSerializer : KSerializer<Geolocation> {
    override val descriptor: SerialDescriptor = SerialDescriptor("f.q.d.n.Geolocation", AbbreviatedGeolocation.serializer().descriptor)

    override fun serialize(encoder: Encoder, value: Geolocation) {
        encoder.encodeSerializableValue(AbbreviatedGeolocation.serializer(), AbbreviatedGeolocation(value.latitude, value.longitude))
    }

    override fun deserialize(decoder: Decoder): Geolocation {
        val value = decoder.decodeSerializableValue(AbbreviatedGeolocation.serializer())
        return Geolocation(value.lat, value.lng)
    }
}
and mark specific use-sites with
@Serializable(with = AbbreviatedGeolocationSerializer::class)
as necessary
l
If you’re only getting responses, I believe the SerialName annotation will match either name, which should be less work than a custom serializer.
e
no, it only matches one name. there is @JsonNames which can match multiple, but is JSON-specific