When jackson object is converted to json, It is NULL and does not participate in serialization summary. jacksonjson
Add dependency first
<Dependency>
<GroupId> com. google. code. gson </groupId>
<ArtifactId> gson </artifactId>
</Dependency>
Method 1: Use @ JsonInclude (JsonInclude. Include. NON_NULL) on the object)
1. if it is placed on an attribute, if it is NULL, it is not involved in serialization;
2. If it is placed on the class, it will take effect for all the attributes of the class;
Parameter meaning:
JsonInclude. Include. ALWAYS default
JsonInclude. Include. NON_DEFAULT attribute is default value not serialized
The JsonInclude. Include. NON_EMPTY attribute is NULL ("") or NULL is not serialized.
The property of JsonInclude. Include. NON_NULL is NULL and is not serialized.
Before use
After use
Method 2: If you do not want to add such a configuration every time, you can configure a global definition in application. yml, which takes effect by default.
spring: jackson: default-property-inclusion: non_null
Method 3: set through the ObjectMapper object. The following is a test case.
@ Testpublic void test () throws JsonProcessingException {ResultVo resultVo = new ResultVo (); resultVo. setCode (0); resultVo. setMsg ("succeeded"); ObjectMapper mapper = new ObjectMapper (); mapper. setserializationsion Sion (JsonInclude. include. ALWAYS); // default String json = mapper. writeValueAsString (resultVo); System. out. println (json); mapper = new ObjectMapper (); mapper. setserializationsion Sion (JsonInclude. include. NON_NULL); // The property is NULL. json = mapper is not serialized. writeValueAsString (resultVo); System. out. println (json); Map map = new HashMap (); map. put ("code", 0); map. put ("msg", "successful"); map. put ("data", null); json = mapper. writeValueAsString (map); System. out. println (json );}
Print as follows:
{"Code": 0, "msg": "successful", "data": null} {"code": 0, "msg ": "successful"} {"msg": "successful", "code": 0, "data": null}
Note: ObjectMapper only works for VO and does not work for Map List.
1. If a field must be returned, you can give the default value (such as string ""; list []) at the beginning of the object class to avoid null.
2. When the jackson object is converted to json, @ JsonIgnore is used to place an attribute on this attribute when it is not serialized.