https://kotlinlang.org logo
#serialization
Title
# serialization
b

Brent Beardsley

10/12/2022, 11:31 PM
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

ephemient

10/12/2022, 11:48 PM
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

Landry Norris

10/13/2022, 12:54 PM
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

ephemient

10/13/2022, 1:02 PM
no, it only matches one name. there is @JsonNames which can match multiple, but is JSON-specific
6 Views