Add dependencies first
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> </dependency>
Method 1. Use @JsonInclude(JsonInclude.Include.NON_NULL) on the entity
1. If it is placed on an attribute, if the attribute is NULL, it will not participate in serialization;
2. If it is placed on a class, it will work on all attributes of this class;
Parameter meaning:
- JsonInclude.Include.ALWAYS 默认
- The JsonInclude.Include.NON_DEFAULT property is not serialized by default
- JsonInclude.Include.NON_EMPTY property is empty ("") or NULL will not serialize
- JsonInclude.Include.NON_NULL property is NULL not serialized
before use
after use
Method 2. If you don't want to add this every time, you can configure the global definition in application.yml, which will take effect by default
spring:
jackson:
default-property-inclusion: non_null
Method 3. Set through the ObjectMapper object, 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);//默认 String json = mapper.writeValueAsString(resultVo); System.out.println(json); mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // The property is NULL and does not serialize json = mapper.writeValueAsString(resultVo); System.out.println(json); Map map = new HashMap(); map.put("code",0); map.put("msg","成功"); map.put("data",null); json = mapper.writeValueAsString(map); System.out.println(json); }
It prints as follows:
{"code":0,"msg":"成功","data":null} {"code":0,"msg":"成功"} {"msg":"成功","code":0,"data":null}
Note: ObjectMapper only works on VO; it does not work on Map List
1. If the field must be returned, you can give a default value (such as string ""; list [] ) at the beginning of the entity class to avoid null
2. When a jackson entity is converted to json, when a property does not participate in serialization, use @JsonIgnore on the property