Hi Jackson community!
Our front-end colleague do not want to get null from back-end, and I tried to overwrite some kinds of null as default values. Here are 3 kinds of them: String, Collection and array. And I have tried some approaches, like setNullSerializer, overwrite CollectionSerializer, but not fits well.
Another way to achieve this is using reflection to replace a default value to null properties before serialization, but I don't prefer this because it would reduce server performance.
It seems to be a common requirement. So it would be great if jackson supports this feature.
I am not sure how this could be achieved in a way compatible with existing configuration operations.
I think that this can really split in two parts because String handling (or in general, scalar types) is quite separate from structured/array serialization.
Your best choice currently is probably use of @JsonSerialize(nullsUsing = MyNullSerializer) -- not necessarily directly, but by overriding method findNullSerializer(Annotated) in JacksonAnnotationIntrospector (or just custom AnnotationIntrospector), applying on case of AnnotatedClass that matches types you are interested in.
I will keep this open in case someone has good ideas on how this should be exposed via API since that is the big challenge.
@bungder have you tried objectMapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT)? or JsonInclude.Include.NON_EMPTY?
@rfoltyns Yes, but it just made null properties disappeared
Can there be a serialization flag similar to the ones here: https://github.com/FasterXML/jackson-databind/wiki/Serialization-features#datatype-specific-serialization
perhaps WRITE_NULL_COLLECTION_AS_EMPTY_ARRAY
As per the annotations, deserialization already has this pretty nice annotation / property: @JsonSetter(nulls=...)
maybe we can have something similar for @JsonGetter?
Are these all bigger API changes that require 3.x?
I do not think adding new SerializationFeatures is a good way to handle various transmutations unfortunately. But I do not have good story on alternative ways.
I will note that there is desire to configure serialization of nulls, similar to mechanism mentioned above.
Also, for specific case of JsonNode serialization, I do have plans on introducing simple JsonNodeFeature which may cover output for Tree Model:
https://github.com/FasterXML/jackson-future-ideas/wiki/JSTEP-3