I have a class like this:
@Serializable
data class MyClass(
val prop1: Int,
val prop2: Int?
)
When prop2 is null, I want to serialize this class without including the prop2 property. I can do this like this:
val json = Json { explicitNulls = false }
json.encodeToString(MyClass(42, null)) // gives {"prop1": 42}
Unfortunately, there are many places in a large project that serialize this class, and currently they just use Json.encodeToString
which includes the nulls explicitly.
How can I enforce the serialization of this class to not serialize nulls? I need this to apply just to this class; other serializable classes in the project need to continue to have explicit nulls.
CodePudding user response:
If you can give the selected fields a default of null
, then you can use the EncodeDefault annotation:
@Serializable
data class MyClass(
val prop1: Int,
@EncodeDefault(NEVER) val prop2: Int? = null
)
This will avoid encoding prop2
if it is null, irrespective of the setting of the encodeDefaults
property of the Json serializer you use when you serialize your class instance.