package com.unis.framework.jackson.core.databind;

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

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import static com.unis.framework.common.util.date.DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND;

/**
 * 自定义序列化器:
 *  LocalDateTime类型对象返回给前端时，返回的时间格式为：yyyy-MM-dd HH:mm:ss
 *  应用:在需要转换的字段上添加:@JsonSerialize(using = CustomLocalDateTimeSerializer.class) // 使用自定义序列化器
 */
public class StringLocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND);

    @Override
    public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value != null) {
            gen.writeString(value.format(formatter));
        } else {
            gen.writeNull();
        }
    }
}