java8中java.time.LocalDateTime的json格式化

示例项目为spring boot构建

步骤1:在gradle或者maven中添加 jackson-datatype-jsr310 依赖库

例如gradle: 

compile 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310'

步骤2:

在实体类属性上加注解 @JsonFormat

com.fasterxml.jackson.annotation.JsonFormat;

到此为止已经可以将LocalDate、LocalTime、LocalDateTime等正确格式化并输出到view,但是如果要让Spring MVC接受到字符串自动转化为LocalDateTime类型的话还需以下一步操作。

扫描二维码关注公众号,回复: 363063 查看本文章

步骤3:注册格式化日期的Bean

@Configuration
public class LocalDateTimeFormatConfig {

    @Bean
    public Formatter<LocalDate> localDateFormatter() {
        return new Formatter<LocalDate>() {
            @Override
            public String print(LocalDate object, Locale locale) {
                return object.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            }

            @Override
            public LocalDate parse(String text, Locale locale) throws ParseException {
                return LocalDate.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            }
        };
    }

    @Bean
    public Formatter<LocalDateTime> localDateTimeFormatter() {
        return new Formatter<LocalDateTime>() {
            @Override
            public String print(LocalDateTime object, Locale locale) {
                return object.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }

            @Override
            public LocalDateTime parse(String text, Locale locale) throws ParseException {
                return LocalDateTime.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }
        };
    }

    @Bean
    public Formatter<LocalTime> localTimeFormatter() {
        return new Formatter<LocalTime>() {
            @Override
            public String print(LocalTime object, Locale locale) {
                return object.format(DateTimeFormatter.ofPattern("HH:mm:ss"));
            }

            @Override
            public LocalTime parse(String text, Locale locale) throws ParseException {
                return LocalTime.parse(text, DateTimeFormatter.ofPattern("HH:mm:ss"));
            }
        };
    }

}

这里用的是java config的写法,使用xml注册也是可以的。

猜你喜欢

转载自endless2009.iteye.com/blog/2382234