springboot 使用JsonSerializer将Date转为long 时间戳 另外json去掉为null的属性

写一个转换类

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.util.Date;

/**
 * Date转为long 单位:秒
 */
public class DateToLongSerializer extends JsonSerializer<Date> {
    @Override
    public void serialize(Date date, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        gen.writeNumber(date.getTime() / 1000);
    }
}

然后可以设置属性

/**
 * Date转为long型,单位为秒
 * JsonSerialize,后面为自己写的类名
 */
@JsonSerialize(using = DateToLongSerializer.class)
private Date createTime;

@JsonSerialize(using = DateToLongSerializer.class)
private Date updateTime;

结果

springboot 使用JsonSerializer将Date转为long 时间戳 另外json去掉为null的属性

json去掉为null的属性:

在类加上注解

springboot 使用JsonSerializer将Date转为long 时间戳 另外json去掉为null的属性

如果要全部的json都生效,可以在配置文件中设置

springboot 使用JsonSerializer将Date转为long 时间戳 另外json去掉为null的属性



还有,如果要返回为空,不为null,可以这样设置

private String msg = "";

private List<OrderDetail> orderDetailList=new ArrayList<>();

返回结果:

springboot 使用JsonSerializer将Date转为long 时间戳 另外json去掉为null的属性

springboot 使用JsonSerializer将Date转为long 时间戳 另外json去掉为null的属性