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 there are fields in Java objects that do not wish to be serialized, we can use the @JsonIgnore annotation in the Jackson library. The @JsonIgnore can be used at the field level, for ignoring fields during the serialization and deserialization.
To ignore individual properties, use the [JsonIgnore] attribute. You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options: Always - The property is always ignored.
The Jackson @JsonIgnore annotation can be used to ignore a certain property or field of a Java object. The property can be ignored both when reading JSON into Java objects and when writing Java objects into JSON.
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); // "{}"
The fact is that in Java the class loader will set to the default value all not initialized primitive properties (int = 0, boolean = false etc...), so you can't distinguish them from those set explicitly by your app. In my opinion you have two options:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With