I have a system where explicitly null fields are different from absent fields in JSON. What would be the best way to represent this in Java for Jackson serialization?
For example, I have a data object like
class Data {
public String string;
public String other;
}
By default, Jackson serializes null fields so new ObjectMapper().writeValueAsString(new Data()) results in {"string":null,"other":null}. However, I would like this to result in {} as the fields were "unset." Obviously, in java they are null, but I'm looking for a way around that.
If I were to do new ObjectMapper().wirteValueAsString(new Data(null, null)), I want that to result in {"string":null,"other":null}. And only the "string" field to result in {"string":"value"}.
The only way I can think of right now is to have booleans for each field and use a custom serializer to check the booleans but that seems pretty messy. Is there an easier way to do this?
Edit: This is not about not serializing null values. I want null values to be serialized if the field was explicitly set to null.
I thought maybe I could use Optionals and Include.NON_ABSENT, but unfortunately this does not work either as Jackson treats an Optional reference to null the same as Optional.empty().