首页 文章

Spring Boot中的JSON Java 8 LocalDateTime格式

提问于
浏览
82

我在Spring Boot Application中格式化Java 8 LocalDateTime时遇到了一个小问题 . 使用“正常”日期我没有问题,但LocalDateTime字段转换为以下内容:

"startDate" : {
    "year" : 2010,
    "month" : "JANUARY",
    "dayOfMonth" : 1,
    "dayOfWeek" : "FRIDAY",
    "dayOfYear" : 1,
    "monthValue" : 1,
    "hour" : 2,
    "minute" : 2,
    "second" : 0,
    "nano" : 0,
    "chronology" : {
      "id" : "ISO",
      "calendarType" : "iso8601"
    }
  }

虽然我想将其转换为:

"startDate": "2015-01-01"

我的代码看起来像这样:

@JsonFormat(pattern="yyyy-MM-dd")
@DateTimeFormat(iso = DateTimeFormat.ISO.TIME)
public LocalDateTime getStartDate() {
    return startDate;
}

但是上述任何一个注释都不起作用,日期会像上面那样被格式化 . 建议欢迎!

8 回答

  • 106

    这里有maven,因此您可以在 Spring 季启动升级之间生存

    <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
            <version>${jackson.version}</version>
    </dependency>
    
  • 2

    我终于找到here怎么做了 . 要修复它,我需要另一个依赖:

    compile("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.4.0")
    

    通过包含这种依赖性,Spring将自动为它注册一个转换器,如here所述 . 之后,您需要将以下内容添加到application.properties:

    spring.jackson.serialization.write_dates_as_timestamps=false
    

    这将确保使用正确的转换器,并且日期将以 2016-03-16T13:56:39.492 的格式打印

    仅在您想要更改日期格式时才需要注释 .

  • 1

    我添加了 com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.6.1 依赖项,我开始按以下格式获取日期:

    "birthDate": [
        2016,
        1,
        25,
        21,
        34,
        55
      ]
    

    这不是我想要的,但我越来越近了 . 然后我添加了以下内容

    spring.jackson.serialization.write_dates_as_timestamps=false
    

    到application.properties文件,它给了我正确的格式,我需要 .

    "birthDate": "2016-01-25T21:34:55"
    
  • 75

    1)依赖性

    compile group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-jsr310', version: '2.8.8'
    

    2)具有日期时间格式的注释 .

    public class RestObject {
    
        private LocalDateTime timestamp;
    
        @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        public LocalDateTime getTimestamp() {
            return timestamp;
        }
    }
    

    3)Spring Config .

    @Configuration
    public class JacksonConfig {
    
        @Bean
        @Primary
        public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
            System.out.println("Config is starting.");
            ObjectMapper objectMapper = builder.createXmlMapper(false).build();
            objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
            return objectMapper;
        }
    }
    
  • 8

    我找到了另一种解决方案,您可以将其转换为您想要的任何格式并应用于所有LocalDateTime数据类型,并且您不必在每个LocalDateTime数据类型之上指定@JsonFormat . 首先添加依赖项:

    <dependency>
        <groupId>com.fasterxml.jackson.datatype</groupId>
        <artifactId>jackson-datatype-jsr310</artifactId>
    </dependency>
    

    添加以下bean:

    @Configuration
    public class Java8DateTimeConfiguration {
        /**
         * Customizing
         * http://docs.spring.io/spring-boot/docs/current/reference/html/howto-spring-mvc.html
         *
         * Defining a @Bean of type Jackson2ObjectMapperBuilder will allow you to customize both default ObjectMapper and XmlMapper (used in MappingJackson2HttpMessageConverter and MappingJackson2XmlHttpMessageConverter respectively).
         */
        @Bean
        public Module jsonMapperJava8DateTimeModule() {
            val bean = new SimpleModule();
    
            bean.addDeserializer (ZonedDateTime.class, new JsonDeserializer<ZonedDateTime>() {
                @Override
                public ZonedDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
                    return ZonedDateTime.parse(jsonParser.getValueAsString(), DateTimeFormatter.ISO_ZONED_DATE_TIME);
                }
            });
    
            bean.addDeserializer(LocalDateTime.class, new JsonDeserializer<LocalDateTime>() {
                @Override
                public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
                    return LocalDateTime.parse(jsonParser.getValueAsString(), DateTimeFormatter.ISO_LOCAL_DATE_TIME);
                }
            });
    
            bean.addSerializer(ZonedDateTime.class, new JsonSerializer<ZonedDateTime>() {
                @Override
                public void serialize(
                        ZonedDateTime zonedDateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
                        throws IOException {
                    jsonGenerator.writeString(DateTimeFormatter.ISO_ZONED_DATE_TIME.format(zonedDateTime));
                }
            });
    
            bean.addSerializer(LocalDateTime.class, new JsonSerializer<LocalDateTime>() {
                @Override
                public void serialize(
                        LocalDateTime localDateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
                        throws IOException {
                    jsonGenerator.writeString(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(localDateTime));
                }
            });
    
            return bean;
        }
    }
    

    在您的配置文件中添加以下内容:

    @Import(Java8DateTimeConfiguration.class)
    

    只要您使用spring创建的objectMapper,这将序列化和反序列化所有属性LocalDateTime和ZonedDateTime .

    您为ZonedDateTime获取的格式为:“2017-12-27T08:55:17.317 02:00 [亚洲/耶路撒冷]”对于LocalDateTime是:“2017-12-27T09:05:30.523”

  • 6

    这项工作很好:

    添加依赖项:

    <dependency>
        <groupId>com.fasterxml.jackson.datatype</groupId>
        <artifactId>jackson-datatype-jdk8</artifactId>
    </dependency>
    

    添加注释:

    @JsonFormat(pattern="yyyy-MM-dd")
    

    现在,您必须获得正确的格式 .

    要使用对象映射器,您需要注册JavaTime

    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JavaTimeModule());
    
  • 26

    写这个答案也是对我的提醒 .

    我在这里结合了几个答案,最后我使用了类似的东西 . (我使用的是SpringBoot 1.5.7和Lombok 1.16.16)

    @Data
    public Class someClass {
    
       @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
       @JsonSerialize(using = LocalDateTimeSerializer.class)
       @JsonDeserialize(using = LocalDateTimeDeserializer.class)
       private LocalDateTime someDate;
    
    }
    
  • 0

    @JsonDeserialize(using= LocalDateDeserializer.class) 对我来说不适用于以下依赖项 .

    <dependency>
        <groupId>com.fasterxml.jackson.datatype</groupId>
        <artifactId>jackson-datatype-jsr310</artifactId>
        <version> 2.9.6</version>
    </dependency>
    

    我使用下面的代码转换器将日期反序列化为 java.sql.Date .

    import javax.persistence.AttributeConverter;
    import javax.persistence.Converter;
    
    
    @SuppressWarnings("UnusedDeclaration")
    @Converter(autoApply = true)
    public class LocalDateConverter implements AttributeConverter<java.time.LocalDate, java.sql.Date> {
    
    
        @Override
        public java.sql.Date convertToDatabaseColumn(java.time.LocalDate attribute) {
    
            return attribute == null ? null : java.sql.Date.valueOf(attribute);
        }
    
        @Override
        public java.time.LocalDate convertToEntityAttribute(java.sql.Date dbData) {
    
            return dbData == null ? null : dbData.toLocalDate();
        }
    }
    

相关问题