andylamax
03/30/2023, 12:08 PMinterface XY {
val x: Int,
val y: Int
}
@Serializable
data class Point(
override val x: Int,
override val y: Int
) : XY
a) How do I mark XY
as serializable and that it should use Point.serializer()
during serialization?
b) Suppose I have a class Vehicle
@Serializable
class Car(
val position: XY
)
How do I mark Car::position
to use Point.serializer()
as it's serializer?
c) Suppose I have a class Point3
like so
@Serializable
data class Point3(
override val x: Int,
override val y: Int,
val x: Int = 0
) : XY
How do I mark Car::position
in part (b) of the question to use Point3.serializer()
as it's serialzer?Daniel
03/30/2023, 12:57 PMinterface Hashable {
@Serializable
@SerialName("h")
val hash: String
}
@Serializable
data class Entity(val id: Int, override val hash: String): Hashable
interface XY {
val x: Int
val y: Int
}
object XYSerializer : KSerializer<XY> {
override val descriptor: SerialDescriptor
get() = //TODO
override fun deserialize(decoder: Decoder): XY {
//TODO
}
override fun serialize(encoder: Encoder, value: XY) {
//TODO
}
}
@Serializable
data class Car(
@Serializable(with = XYSerializer::class)
val position: XY
)
andylamax
03/30/2023, 1:24 PMPaul Woitaschek
03/30/2023, 6:46 PMfun main() {
val json = Json {
serializersModule = SerializersModule {
polymorphic(XY::class, Point::class, Point.serializer())
}
}
println(json.encodeToString(Car.serializer(), Car(Point(42, 24))))
}
object XYSerializer : KSerializer<XY> {
override fun deserialize(decoder: Decoder): XY = Point.serializer().deserialize(decoder)
override val descriptor: SerialDescriptor = Point.serializer().descriptor
override fun serialize(encoder: Encoder, value: XY) {
encoder.encodeSerializableValue(Point.serializer(), Point(value.x, value.y))
}
}
andylamax
03/30/2023, 10:58 PMYour option c) is very error prone. Point3 has more information than XY so if you go that route, it will always crash if XY isn’t Point3.How will it crash? I though
Point3
has a default z argument. and it will always be an instance of XYXY
can be purely serialized with Point.serializer()
. What I am asking now is, "Is there a current way to tell the compiler to just go ahead and use `Point.serializer()`" to Serialize XY
Instead of having to write this custom serializer down?.
In better terms, the compiler has already generated a serializer that can easily serialize and deserialize XY, it feels like there should be an easier way to tell it, "for this particular case, go ahead and use this other serializer you have already generated".
This might not be a currently available feature. But there sure is a use case for it