Reputation: 86627
I'm outputting some database results via json
webservice. Simple as:
@GetMapping(produces = "application/json")
public List<Map<String, Object>> get(Param params) {
return jdbcTemplate.queryForList(sql, params)
}
Problem: java.sql.Timestamp
is converted to format 2018-04-26T07:52:02.000+0000
, while the plain database output would be 2018-04-26 07:52:02.0
.
Question: is there any configuration property to tell spring to just pass through the native timestamp received from the database, instead of converting it with jackson
logic?
I want to change the java.sql.Timestamp
format globally.
Important: please don't suggest any annotations! I don't have any bean/pojo, I'm just returning the plain database result as a Map
.
Upvotes: 1
Views: 4312
Reputation: 130837
I want to change the
java.sql.Timestamp
format globally.
Set a date format to your ObjectMapper
instance:
ObjectMapper mapper = new ObjectMapper();
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S"));
In Spring applications, you can expose the ObjectMapper
instance as a bean:
@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S"));
return mapper;
}
In Spring Boot you can use the property spring.jackson.date-format
to define the date format:
spring.jackson.date-format: yyyy-MM-dd HH:mm:ss.S
For more details on the common application properties, refer to the documentation.
Consider the following code:
Map<String, Object> data = new HashMap<>();
data.put("date", new Timestamp(ZonedDateTime.now().toInstant().toEpochMilli()));
System.out.println(mapper.writeValueAsString(data));
It will print:
{"date":"2018-04-26 07:25:14.408"}
Upvotes: 6
Reputation: 25136
Or if you need this as a 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;
}
Upvotes: 0