簡體   English   中英

傑克遜更改時間戳格式

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM