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"
}
During deserialization, I want to consume latitude and longitude and create a single object called Location. In other words, I want to parse this json with POJO classes similar to:
@Serializable
data class CheckInRecord(val id: String, val date: String, val location: Location)
@Serializable
data class Location(val latitude: String, val longitude: String)
How can I achieve this?
You can approach this with the surrogate serializer pattern, which is in exactly the same fashion as in the question I answered earlier today, but in reverse (as that was about encoding rather than decoding).
To apply the pattern, you start off writing a serializable surrrogate object to match the JSON you want:
This gives you the tools to implement the
KSerializerinterface for your target classCheckInRecordby 'plugging in the gaps' to translate the surrogate to your desired end object (and back, for completeness):Finally, you must tell the framework to use your new serializer on
CheckInRecord(note we don't even need to makeLocationserializable with this approach):Now we can try it all out:
Which prints what we expect, showing
CheckInRecordwas successfully instantiated: