2015-11-11 46 views
1

我正在使用Jackson將POJO序列化爲JSON,但在格式化日期時遇到困難。我也碰到過這個wiki上傑克遜的網站:http://wiki.fasterxml.com/JacksonFAQDateHandlingJackson - 序列化日期對象

通過這篇文章,我做了以下內容:

objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false); 

這在ISO-8601格式,這正是我想要的打印日期的對象。除了「+0000」。根據ISO-8601格式,+ hhmm是UTC的時間偏移量。傑克遜有辦法禁用時間偏移嗎?或者我只需要指定一個自定義的日期格式?

+0

另見:https://stackoverflow.com/questions/45276807/iso8601-with-milliseconds-in-json-using-jackson –

回答

2

我認爲你最好的選擇是在序列化時傳遞一個新的日期格式。例如:

final ObjectMapper objectMapper = new ObjectMapper(); 
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm")); 

基礎上JavaDocs on github這給一些洞察到日期格式是如何確定的,沒有指定自己的,我想你只能要麼使用數字時間戳或內置在傑克遜定義ISO格式。參考文檔:

/** 
    * Feature that determines whether Date (and date/time) values 
    * (and Date-based things like {@link java.util.Calendar}s) are to be 
    * serialized as numeric timestamps (true; the default), 
    * or as something else (usually textual representation). 
    * If textual representation is used, the actual format is 
    * one returned by a call to 
    * {@link com.fasterxml.jackson.databind.SerializationConfig#getDateFormat}: 
    * the default setting being {@link com.fasterxml.jackson.databind.util.StdDateFormat}, 
    * which corresponds to format String of "yyyy-MM-dd'T'HH:mm:ss.SSSZ" 
    * (see {@link java.text.DateFormat} for details of format Strings). 
    *<p> 
    * Note: whether this feature affects handling of other date-related 
    * types depend on handlers of those types, although ideally they 
    * should use this feature 
    *<p> 
    * Note: whether {@link java.util.Map} keys are serialized as Strings 
    * or not is controlled using {@link #WRITE_DATE_KEYS_AS_TIMESTAMPS}. 
    *<p> 
    * Feature is enabled by default, so that date/time are by default 
    * serialized as timestamps. 
    */ 
    WRITE_DATES_AS_TIMESTAMPS(true), 
+0

我怕這將是我唯一的選擇,但我只是想確定一下,因爲我對傑克遜不是很熟悉。 – user972276

相關問題