How to deserialize a json field with varying type in kotlinx serialization?

50 Views Asked by At

Consider the following json structure representing a basic check-in information

{
  "id": "53481198005",
  "date": "1995-01-01 00:00:00",
  "latitude": "50.765391",
  "longitude": "60.765391"
}

When API doesn't have latitude and longitude information, it sends them in int type with value 0 like this:

{
  "id": "53481198005",
  "date": "1995-01-01 00:00:00",
  "latitude": 0,
  "longitude": 0
}

And of course, when I try to deserialize it with the following class, it throws an exception.

@Serializable
data class CheckInRecord(
    val id: String,
    val date: String,
    val latitude: String?,
    val longitude: String?
)

Exception:

kotlinx.serialization.json.internal.JsonDecodingException: Unexpected JSON token at offset 457: Expected quotation mark '"', but had '0' instead

I want to deserialize them only if they are string. If they are int, I want to make them null. I already considered implementing a custom deserializer like in kotlinx-deserialization documentation. For example, checking field type by doing the following is possible by reaching JsonDecoder

val jsonInput = decoder as? JsonDecoder ?: error("error")
val json = jsonInput.decodeJsonElement().jsonObject
val isLongitudeString = json["longitude"]?.jsonPrimitive?.isString

but I want to implement a common deserializer for this kind of fields without repeating deserializer code. Above code, "longitude" is a hardcoded value making me implement multiple deserializers.

How can achieve this or something similar?

0

There are 0 best solutions below