Spring Boot 2.x 输出Json对象时对LocalDateTime的格式化

定义LocalDateTimeSerializer

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

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

public class LocalDateTimeSerializer extends StdSerializer {
    private static final long serialVersionUID = 1L;

    private String dataFormat;

    protected LocalDateTimeSerializer(Class t, String dateFormat) {
        super(t);

        this.dataFormat = dateFormat;
    }

    @Override
    public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.writeString(DateTimeFormatter.ofPattern(dataFormat).format(value));

    }

}

定义LocalDateTimeJacksonConfiguration

import java.time.LocalDateTime;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.jackson.JacksonProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import com.fasterxml.jackson.databind.module.SimpleModule;

@Configuration
@ConditionalOnClass({ Jackson2ObjectMapperBuilder.class, LocalDateTime.class })
public class LocalDateTimeJacksonConfiguration {
    @Bean
    public SimpleModule localDateTimeSerializationModule(JacksonProperties jacksonProperties) {
        SimpleModule module = new SimpleModule();

        module.addSerializer(LocalDateTime.class,
                new LocalDateTimeSerializer(LocalDateTime.class, jacksonProperties.getDateFormat()));

        return module;
    }
}

你可能感兴趣的:(Spring Boot 2.x 输出Json对象时对LocalDateTime的格式化)