We have the need to distinguish between an optional fields vs. nullable fields (i.e when a field is present, that it could be nullable) when serializing Kotlin data classes to JSON using GSON.
The initial thought was to model the optional field as a generic:
class Optional<T>(val isPresent: Boolean = false, val value: T) {}
That would permit representing it in the following serializable data class:
data class SimpleRequest (
val a: Int = 0,
val b: Optional<String> = Optional<String>(value = "")
val c: Optional<String> = Optional<String>(value = "")
val d: Int? = null,
val e: Optional<Int?> = Optional<Int?>(value = null)
)
That should result in the following serialized variants (with null serialization enabled):
SimpleRequest(c = Optional<String>(true, "Hello"), e = Optional(true, null))
{
"a": 0,
"c": "Hello",
"d": null,
"e": null
}
Is this possible?