First join the dependency
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
Method One, use @JsonInclude on the entity (JsonInclude.Include.NON_NULL)
1, if placed on the property , if the property is null does not participate in serialization;
2, if placed on the class , that the entire properties of the class function;
Parameter meaning:
JsonInclude.Include.ALWAYS Default
The JsonInclude.Include.NON_DEFAULT property is not serialized as the default value
JsonInclude.Include.NON_EMPTY property is empty ("") or null is not serialized
JsonInclude.Include.NON_NULL property is NULL not serialized
Before using
After use
Method Two, if you do not want to add this every time, you can configure the global definition in APPLICATION.YML, this default is effective
Spring
Jackson
Default-property-inclusion:non_null
Method Three, through the Objectmapper object to set up, the following is the test case
@Test public void Test () throws jsonprocessingexception { Resultvo resultvo = new Resultvo (); Resultvo.setcode (0); Resultvo.setmsg ("Success"); Objectmapper mapper = new Objectmapper (); Mapper.setserializationinclusion (JsonInclude.Include.ALWAYS);//default String JSON = mapper.writevalueasstring ( RESULTVO); SYSTEM.OUT.PRINTLN (JSON); Mapper = new Objectmapper (); Mapper.setserializationinclusion (JsonInclude.Include.NON_NULL); The property is null not serialized JSON = mapper.writevalueasstring (RESULTVO); SYSTEM.OUT.PRINTLN (JSON); }
Print as follows:
{"code": 0, "msg": " success ", "data":null} {"code": 0, "msg": " success "}
Jackson entity is null when transcoding to JSON does not participate in serialization rollup