【问题标题】:How to format the json date format using spring boot如何使用spring boot格式化json日期格式
【发布时间】:2015-05-18 14:44:15
【问题描述】:

我正在开发 Spring Boot 和 gradle 以创建休息服务。现在我需要以“yyyy-MM-dd”的形式格式化json日期,即格式应该是dateOfBirth:“16-03-2015”,但我得到的是“dateOfBirth:-751181400000”。我在 Apllication.java 类中添加了以下代码,但仍然无法获得所需的输出。

@Bean
@ConditionalOnClass({ ObjectMapper.class, Jackson2ObjectMapperBuilder.class })
public Jackson2ObjectMapperBuilder jacksonBuilder()
{ 
    Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder(); 
    builder.indentOutput(true).dateFormat(new SimpleDateFormat("yyyy-MM-dd")); 
    return builder; 
}

和Application.java:

@Configuration
@Import(SubjectServiceConfig.class)
@EnableAutoConfiguration
@EnableEurekaClient
@ComponentScan({"com.billing"})
@EnableWebMvc
@EnableHypermediaSupport(type = EnableHypermediaSupport.HypermediaType.HAL)
public class Application {
public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}
}

请帮我解决这个问题。

【问题讨论】:

  • 对于一个给定的日期,你得到了什么输出以及期望的输出是什么?
  • 您好,Alvaro 很抱歉没有提供详细信息。我需要 dateOfBirth: "16-03-2015" 但我得到 dateOfBirth: -751181400000。
  • 返回日期的 REST 端点的方法签名是什么?
  • 公共响应实体> getBilling(@PathVariable String id)

标签: java json spring rest spring-boot


【解决方案1】:

使用 Spring Boot,您应该能够通过在 application.yml/application.properties 中设置以下属性来设置 Jackson 格式化日期的默认方式:

spring.jackson.date-format= # Date format string (e.g. yyyy-MM-dd HH:mm:ss), or a fully-qualified date format class name (e.g. com.fasterxml.jackson.databind.util.ISO8601DateFormat)

【讨论】:

  • 亚当 感谢您的回复。它仅适用于 Spring-boot,但不适用于 Spring-boot 和 Spring-Hateoas。请帮帮我。或者有没有其他方法可以实现这一点。
  • 在您配置 objectMapper 的位置,确保设置了此序列化功能:objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
  • 它几乎明显
猜你喜欢
  • 2015-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-15
  • 2021-12-15
  • 2019-01-19
  • 2021-09-18
相关资源
最近更新 更多