jackson版本1.6.1html
問題描述以下:序列化時間是比實際時間少8小時java
public class JacksonTest { public static void main(String[] args){ Date date = new Date(); Timestamp timestamp = new Timestamp(date.getTime()); ObjectMapper mapper2 = new ObjectMapper(); mapper2.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z")); StringWriter sw = new StringWriter(); StringWriter sw1 = new StringWriter(); JsonGenerator gen; JsonGenerator gen1; try { gen = new JsonFactory().createGenerator(sw); gen1 = new JsonFactory().createGenerator(sw1); mapper2.writeValue(gen, date); mapper2.writeValue(gen1, timestamp); gen.close(); } catch (IOException e) { } finally { } System.out.println(timestamp); System.out.println(sw.toString()); System.out.println(sw1.toString()); } }
輸出:app
2015-12-03 19:01:40.983 "2015-12-03 11:01:40 +0000" "2015-12-03 11:01:40 +0000"
問題緣由:spa
jackson在序列化時間時是按照國際標準時間GMT進行格式化的,而在國內默認時區使用的是CST時區,二者相差8小時,調試
經調試,這應該屬於Jackson的bug,以下是ObjectMapper源碼
code
/** * Base settings contain defaults used for all {@link ObjectMapper} * instances. */ protected final static BaseSettings DEFAULT_BASE = new BaseSettings( null, // can not share global ClassIntrospector any more (2.5+) DEFAULT_ANNOTATION_INTROSPECTOR, STD_VISIBILITY_CHECKER, null, TypeFactory.defaultInstance(), null, StdDateFormat.instance, null, Locale.getDefault(), // TimeZone.getDefault() TimeZone.getTimeZone("GMT"), Base64Variants.getDefaultVariant() // 2.1 );
jackson沒有去默認的時區,而是取GMT時區。orm
解決辦法:重寫ObjectMapper類,包路徑和jackson的包路徑相同。htm