【问题标题】:How to Use Spring Boot's 'spring.jackson.date-format' Property?如何使用 Spring Boot 的“spring.jackson.date-format”属性?
【发布时间】:2017-09-23 03:38:49
【问题描述】:

根据Current SpringBoot Reference Guide,如果我设置spring.jackson.date-format属性,它将:Date format string or a fully-qualified date format class name. For instance 'yyyy-MM-dd HH:mm:ss'

但是,它不适用于 Spring Boot 1.5.3。

为了演示,从这个类开始:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Instant;

@SpringBootApplication
public class DemoApplication {
  public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
  }
}

@RestController
class NowController{

  @GetMapping("/now")
  Instant getNow(){
    return Instant.now();
  }

}

还有这个src/main/resources/application.properties

spring.jackson.date-format=dd.MM.yyyy

还有这个build.gradle

buildscript {
    ext {
        springBootVersion = '1.5.3.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'org.springframework.boot'

version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile('org.springframework.boot:spring-boot-starter-web')
    compile('com.fasterxml.jackson.datatype:jackson-datatype-jdk8')
    compile('com.fasterxml.jackson.datatype:jackson-datatype-jsr310')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

我得到以下信息:

http localhost:8080/now
HTTP/1.1 200 
Content-Type: application/json;charset=UTF-8
Date: Tue, 25 Apr 2017 22:37:58 GMT
Transfer-Encoding: chunked

"2017-04-25T22:37:58.319Z"

请注意,这不是dd.MM.yyyy 指定的格式。如果spring.jackson.date-format 没有按照文档说明工作,还需要其他什么吗?

【问题讨论】:

    标签: spring spring-boot jackson spring-restcontroller spring-rest


    【解决方案1】:

    该属性仅用于java.util.Date 序列化而不是java.time.* 类。

    您可以使用@JsonFormat(pattern="dd.MM.yyyy") 指定按需(每个字段)格式

    创建一个实现 org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer 接口的 bean,并在 ObjectMapper 上为使用更合理格式的 java.time.* 类设置自定义序列化程序。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-07
    • 2021-05-23
    • 2015-04-29
    • 2018-08-12
    • 2021-09-19
    相关资源
    最近更新 更多