[QUESTION] How to conditionally omit a field during serialization?
- Dominant language
- Java
- Stars
- 4.4k
- Forks
- 613
- Avg merge
- 1d 22h
- Merged PRs (30d)
- 6
Description
Hi,
What's the nicest way to conditionally omit a field during serialization?
Let's say I have a class:
```kt
class MyDTO (
@JSONField(name = "id")
id: Int,
@JSONField(name = "key")
key: OmittableString
)
```
```kt
class OmittableString {
value: String?
omit: boolean
}
```
And based on values in `OmittableString` it can serialize to one of:
A. Value is set:
```json
{
"id": 123,
"key": "value"
}
```
B. Value is set to null:
```json
{
"id": 123,
"key": null
}
```
C. Value is omitted:
```json
{
"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!
Contributor guide
Research direction
Start with JSONWriter, which the issue identifies as handling only the value, and trace how the key is emitted for @JSONField members. The work is done when OmittableString can serialize as a value, null, or an omitted key while preserving the id and key names.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- java
- Domain
- backend-api-design
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100