How do I make jackson not serialize primitives with default value
jackson, java, json
Solution
If you're using a recent version of Jackson you can use `JsonInclude.Include.NON_DEFAULT` which 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:
@JsonInclude(Include.NON_DEFAULT)
public class Bean {
private int val;
public int getVal() { return val; }
public void setVal(int val) { this.val = val; }
}
Bean b = new Bean();
b.setVal(0);
new ObjectMapper().writeValueAsString(b); // "{}"
Problem
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"?