In Jackson, it is possible to use JsonSerialize annotation on a POJO in order to prevent null objects from being serialized (@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)). Primitives, however, cannot be set to null, so this annotation doesn’t work for something like an int that hasn’t been touched and defaults to 0.
Is there an annotation that would allow me to say something like “For this class, don’t serialize primitives unless they are different than their default values” or “For this field, don’t serialize it if its value is X”?
If you’re using a recent version of Jackson you can use
JsonInclude.Include.NON_DEFAULTwhich should work for primitives.The downside to this approach is that setting a bean property to its default value will have no effect and the property still won’t be included: