将 Java 时间戳转换为字符串?

Converting a Java Timestamp into a String?

我的 Java 实体中有以下字段:

@JsonProperty
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "start_date")
private Calendar startDate;

通过json发送到前端目前是timestamp

如何将其转换成 string 发送到前端?

您可以使用 @JsonSerialize 注释。

@JsonProperty
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "start_date")
@JsonSerialize(using = CalenderSerializer.class)
private Calendar startDate;

序列化器:

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

public class CalenderSerializer extends StdSerializer<Calendar> {

    private static final long serialVersionUID = 72941023713498596L;
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);

    public CalenderSerializer() {
        this(null);
    }

    public CalenderSerializer(Class<Calendar> t) {
        super(t);
    }

    @Override
    public void serialize(Calendar value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.writeString(sdf.format(value.getTime()));
    }
}