- 空字符串序列化注解方式
将该标记放在属性上,如果该属性为NULL则不参与序列化
如果放在类上边,那对这个类的全部属性起作用
Include.Include.ALWAYS 默认
Include.NON_DEFAULT 属性为默认值不序列化
Include.NON_EMPTY 属性为 空("") 或者为 NULL 都不序列化
Include.NON_NULL 属性为NULL 不序列化
- null转空字符串""
@Bean
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
@Override
public void serialize(Object paramT, JsonGenerator paramJsonGenerator,
SerializerProvider paramSerializerProvider) throws IOException {
//设置返回null转为 空字符串""
paramJsonGenerator.writeString("");
}
});
return objectMapper;
}
- springboot配置方式
#注解方式的优先级高于编码方式
spring.jackson.default-property-inclusion=non_empty
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
- 忽略序列化字段
@JsonProperty(access = JsonProperty.Access.READ_ONLY) 反序列化的时候会处理不会忽略,序列化会忽略(比如请求参数中有字段会读取到,但接口返回时会忽略)
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY) 反序列化的时候会忽略
@JsonIgnore() 反序列化、序列化都会忽略处理
- 转换
方法一:
@JsonFormat(shape = JsonFormat.Shape.STRING) 序列化会转化成string,swagger中会看到就是string类型
方法二:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
@JacksonAnnotationsInside
@JsonSerialize(using = FieldToStringSerializer.class)
public @interface FieldToString {
}
public class FieldToStringSerializer extends JsonSerializer<Object> {
@Override
public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeString(String.valueOf(o));
}
}
@FieldToString
private Long id;
这种方法适合接受、返回都用同一个model,在swagger中看到的是原来的数据类型