[英]Jackson change timestamp format
我正在通过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
。
我想全局更改
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
有关通用应用程序属性的更多详细信息,请参阅文档 。
考虑以下代码:
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 @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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.