使用@JsonSerialize将Date类型序列化成时间戳
根据需求编写序列化方法
package com.liujx.sell.utils.serializer;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.util.Date;
public class Date2LongSerializer extends JsonSerializer<Date> {
@Override
public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
jsonGenerator.writeNumber(date.getTime() / 1000);
}
}
在需要序列化的属性上使用@JsonSerialize注解
@JsonSerialize(using = Date2LongSerializer.class)
private Date updateTime;
使用@JsonInclude注解,将为空的属性设置为不返回前台
在需要不返回空属性的类上加上注解即可:
@JsonInclude(JsonInclude.Include.NON_NULL)
Include枚举类包含有:
ALWAYS,
NON_NULL,
NON_ABSENT,
NON_EMPTY,
NON_DEFAULT,
USE_DEFAULTS;
还可以在application.yml中进行全局配置:
spring:
jackson:
default-property-inclusion: non_null