Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make jackson not serialize primitives with default value

Tags:

java

json

jackson

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"?

like image 802
galactoise Avatar asked Jan 21 '13 08:01

galactoise


People also ask

How do you ignore certain fields based on a serializing object to JSON?

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.

How do I ignore Jsonproperty?

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.

How do I ignore a field in JSON response Jackson?

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.


2 Answers

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); // "{}" 
like image 98
HiJon89 Avatar answered Sep 23 '22 04:09

HiJon89


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:

  • Use corresponding wrapper objects instead of primitives (Integer,Boolean,Long..)
  • As already suggested, define a custom serializer
like image 25
carlo.polisini Avatar answered Sep 23 '22 04:09

carlo.polisini