Imagine we have two data classes Car and CarDoor
data class Car(val doors: List<CarDoor>, val color: String, val maxSpeed: Double)
data class CarDoor(val belongsTo: Car, var isOpen: Boolean)
(Sadly Kotlin does not allow CarDoor to be both an inner class and @Serializable, so I had to pick my battles)
How would we go about using @Serializable to (de)serialize these two classes correctly, without encountering StackOverflowException since they are cyclically related.
Basically, how do I make the belongsTo field of CarDoor transient so that it does not participate in serialization? @Transient does not work because then I'd have to assign an initializing expression to that field.
Edit: the JSON produced should look something like this:
{"doors": [
{"isOpen": false},
{"isOpen": false},
{"isOpen": false},
{"isOpen": true}
], "color": "red", "maxSpeed": 95}
or, and this is even better, to have an identifier of the car inside each car-door, like this:
{"name": "cool-car-1",
"doors": [
{"car": "cool-car-1", "isOpen": false},
{"car": "cool-car-1", "isOpen": false},
{"car": "cool-car-1", "isOpen": false},
{"car": "cool-car-1", "isOpen": true}
], "color": "red", "maxSpeed": 95}