差異處

這裏顯示兩個版本的差異處。

連向這個比對檢視

下次修改
前次修改
java:jackson:annotation:jsonserialize:convertdate [2016/03/10 23:48]
tony 建立
java:jackson:annotation:jsonserialize:convertdate [2023/06/25 09:48] (目前版本)
行 72: 行 72:
 } }
 </​code>​ </​code>​
 +==== Convert to Json ====
 +簡單寫一個測試案例,去驗證序列化後再反序列化的內容會一致:​
 +<code java>
 + @Test
 + public void testDateWithAnnotation() throws Exception {
 + ObjectMapper mapper = new ObjectMapper();​
 +
 + Date d = new Date();
 + Event e = new Event();
 + e.setDate(d);​
 +
 + String ret = mapper.writeValueAsString(e);​
 + System.out.println(ret);​
 + Event newEvent = mapper.readValue(ret,​ Event.class);​
 + assertEquals(d.getTime(),​ newEvent.getDate().getTime());​
 + }
 +</​code>​
 +output:
 +<​code>​
 +{"​date":"​2016-03-10T15:​40:​11.869+0000","​message":​null}
 +</​code>​
 +==== Apply to all Date fields ====
 +上面所敘述的是透過在欄位宣告@JsonSerialize,來達到我們的目的。如果想要讓每一個擁有Date的bean物件都能使用這個格式,可以透過Jackson所提供的Module功能,去設定對應物件的Serializer與Deserializer:​
 +<code java>
 +ObjectMapper mapper = new ObjectMapper();​
 +
 +SimpleModule m = new SimpleModule();​
 +m.addSerializer(Date.class,​ new ISO8601DateSerializer());​
 +m.addDeserializer(Date.class,​ new ISO8601DateDeserializer());​
 +
 +mapper.registerModule(m);​
 +</​code>​
 +==== 後記 ====
 +  - 時間轉換可以透過[[http://​www.joda.org/​joda-time/​|joda-time]]去實作你想要的格式。
 +  - Jackson提供了[[https://​github.com/​FasterXML/​jackson-datatype-joda/​wiki|joda模組]],讓你轉換更容易。
 ===== Reference ===== ===== Reference =====
   * [[http://​stackoverflow.com/​questions/​5471379/​ways-to-convert-unix-linux-time-to-windows-time|ways-to-convert-unix-linux-time-to-windows-time]]   * [[http://​stackoverflow.com/​questions/​5471379/​ways-to-convert-unix-linux-time-to-windows-time|ways-to-convert-unix-linux-time-to-windows-time]]