Skip to content

Instantly share code, notes, and snippets.

@PaulWoitaschek
Created March 30, 2023 18:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PaulWoitaschek/c650466b8bbc0c44797b6b10951918a5 to your computer and use it in GitHub Desktop.
Save PaulWoitaschek/c650466b8bbc0c44797b6b10951918a5 to your computer and use it in GitHub Desktop.
package sandbox.serializationtest
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
@Serializable(with = XYSerializer::class)
interface XY {
val x: Int
val y: Int
}
object XYSerializer : KSerializer<XY> by Point.serializer() as KSerializer<XY>
@Serializable
data class Point(
override val x: Int,
override val y: Int
) : XY
@Serializable
data class Car(
val position: XY
)
fun main() {
val originalCar = Car(Point(42, 24))
val carJson = Json.encodeToString(Car.serializer(), originalCar)
val decodedCar = Json.decodeFromString(Car.serializer(), carJson)
check(originalCar == decodedCar)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment