good morning, I’m sorry if this is a recurring or ...
# serialization
d
good morning, I’m sorry if this is a recurring or a trivial question but it’s my first time I had to write custom serializer/deserializer for a project and i’m a little confused. I have to migrate an old GSON Deserializer for a data class that look like this:
@Serializable(with = PaymentInfoSerializer::class)
data class PaymentInfo(
val id: PaymentId,
val amount: Float,
val paidAt: String?,
val productId: ProductId
)
The last field is a typealias for a Int type but it’s actually an evaluated one. The field is a field taken from an inner Json Object like this:
"product":{"id":74}
so the value is just the id field. The entire json is like this one:
"id":22,"paidAt":null,"amount":720.0,"description":null,"product":{"id":74}
So my problem is that I can’t use simple deserilization with dataclass because I have to keep the code working but i can’t figure out how a map object is actually descripted inside a desirializer. I’have written a descriptor like this but i’m not sure how ti could work as I have no way to tell it to take just the id field inside the map:
override val descriptor: SerialDescriptor =
buildClassSerialDescriptor("PaymentInfo") {
element<PaymentId>("id")
element<Float>("amount")
element<String?>("paidAt", isOptional = true)
element<Map<String, Int>>("product")
}
At the end, i’ve to find a way to tell serilization to do something like this in GSON:
productId = jsonObject.get("product").asJsonObject.get("id").asInt
I've read the doc but I can't find some example that actually seems to fit and since I have to migrate a lot of this custom serializer I'm tring to start with the correct structure. Is there someone who could help? Thanks
r
You should be able to use
JsonObject
as the type
d
Hey, thanks...actually, i'm kinda get what you mean but not sure....you mean inside
descriptor
definition?
r
Yeah and have custom code in your serializer/deserializer functions, but a cleaner solution would be to use a surrogate, I think that’s what I would do. https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/serializers.md#composite-serializer-via-surrogate
Basically have a private/secret correct model matching the json, then your serializer just transform it to the existing public model
d
Oh! thanks man...I'm gonna try that. Thanks