fastjson2
fastjson2 copied to clipboard
[QUESTION] How to conditionally omit a field during serialization?
Hi,
What's the nicest way to conditionally omit a field during serialization?
Let's say I have a class:
class MyDTO (
@JSONField(name = "id")
id: Int,
@JSONField(name = "key")
key: OmittableString
)
class OmittableString {
value: String?
omit: boolean
}
And based on values in OmittableString it can serialize to one of:
A. Value is set:
{
"id": 123,
"key": "value"
}
B. Value is set to null:
{
"id": 123,
"key": null
}
C. Value is omitted:
{
"id": 123
}
I would like to write a serializer for OmittableString that can also do the option C, but on first look, it seems to me that JSONWriter is not the right place to look at, as it's responsible only for the value and not the key.
Context: I'm serializing a request for a 3rd party API, and they use null value to patch existing value to null, and omit field to skip changing existing value.
Thanks in advance!