1

I’m trying to implement functionality that excludes the whole object from the serialization if all inner objects are excluded.

For example when I want to serialize this data class to json

data class Car(val engine: Engine? = null, val size: Size?  = null)
data class Engine(val type: String?  = null, val horsePower: Int?  = null)
data class Size(val size: Int? = null)

Car(engine = Engine(horsePower = null), size = Size(size = 1000))

then I should get the following output (engine is excluded even if it is set)

car {
    size {
        size = 1000
    }
}

Does anyone have any tip on how to achieve this?

user2875643
  • 93
  • 2
  • 3

1 Answers1

5

For kotlinx.serialization use @kotlinx.serialization.Transient

data class Car(
   
   @kotlinx.serialization.Transient
   val engine: Engine? = null
   ...
Eklavya
  • 17,618
  • 4
  • 28
  • 57