杰克逊更改时间戳格式

mem*_*und 1 java spring json spring-mvc jackson

我正在通过json网络服务输出一些数据库结果。简单如下:

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

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

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

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

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

cas*_*lin 6

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

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

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

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

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

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

spring.jackson.date-format: yyyy-MM-dd HH:mm:ss.S
Run Code Online (Sandbox Code Playgroud)

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


考虑以下代码:

spring.jackson.date-format: yyyy-MM-dd HH:mm:ss.S
Run Code Online (Sandbox Code Playgroud)

它将打印:

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