【问题标题】:Jackson change timestamp format杰克逊更改时间戳格式
【发布时间】:2018-04-26 10:58:45
【问题描述】:

我正在通过json webservice 输出一些数据库结果。简单如:

@GetMapping(produces = "application/json")
public List<Map<String, Object>> get(Param params) {
    return jdbcTemplate.queryForList(sql, params)
}

问题:java.sql.Timestamp 被转换为格式2018-04-26T07:52:02.000+0000,而纯数据库输出将是2018-04-26 07:52:02.0

问题:是否有任何配置属性告诉 spring 只传递从数据库接收到的本机时间戳,而不是使用 jackson 逻辑对其进行转换?

我想全局更改java.sql.Timestamp格式。

重要提示:请不要提出任何注释!我没有任何 bean/pojo,我只是将纯数据库结果作为 Map 返回。

【问题讨论】:

  • 您是否已经尝试过@JsonFormat 注释? baeldung.com/jackson-jsonformat
  • 正如所写,我不是在创建 bean。我没有定义可以添加注释的显式字段。我只是直接从查询结果返回数据库行。不涉及 pojo/dto。
  • @narayan-sambireddy 显然不是重复的,因为建议使用注释。正如所写,我不能在这里使用注释!
  • 能否更新一下问题,sn-p 似乎是从 void 方法返回的。

标签: java json spring spring-mvc jackson


【解决方案1】:

我想全局更改java.sql.Timestamp格式。

为您的ObjectMapper 实例设置日期格式:

ObjectMapper mapper = new ObjectMapper();
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S"));

在 Spring 应用程序中,您可以将 ObjectMapper 实例公开为 bean:

@Bean
public ObjectMapper objectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S"));
    return mapper;
}

在 Spring Boot 中,您可以使用属性spring.jackson.date-format 来定义日期格式:

spring.jackson.date-format: yyyy-MM-dd HH:mm:ss.S

有关常见应用程序属性的更多详细信息,请参阅documentation


考虑以下代码:

Map<String, Object> data = new HashMap<>();
data.put("date", new Timestamp(ZonedDateTime.now().toInstant().toEpochMilli()));
System.out.println(mapper.writeValueAsString(data));

它将打印:

{"date":"2018-04-26 07:25:14.408"}

【讨论】:

  • spring.jackson.date-format 属性非常适合,无需添加任何代码。
【解决方案2】:

或者如果你需要这个作为 Spring @Bean

    @Bean
    public JacksonProperties jacksonProperties() {
        JacksonProperties properties = new JacksonProperties();
        properties.setDateFormat("yyyy-MM-dd'T'HH:mm:ss"); // put any pattern you need
        return properties;
    }

【讨论】:

    猜你喜欢
    • 2020-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-05
    • 1970-01-01
    • 2015-05-02
    相关资源
    最近更新 更多