我试图弄清楚如何序列化和反序列化具有特定时区的Calendar对象。我认为Jackson可以尊重我的时区并允许我将Calendar实例保持在指定的时区是合理的。它适用于序列化,但不适用于反序列化。我做错了什么?
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
import java.io.ByteArrayOutputStream;
public class JacksonTimeZoneTest2 {
public Calendar time;
public static void main(String[] args) throws java.io.IOException {
JacksonTimeZoneTest2 test = new JacksonTimeZoneTest2();
test.time = new java.util.GregorianCalendar(2014, Calendar.SEPTEMBER, 1);
ObjectMapper mapper = new ObjectMapper();
SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
sdf.setTimeZone(TimeZone.getTimeZone("CET"));
mapper.setDateFormat(sdf);
ByteArrayOutputStream serialized = new ByteArrayOutputStream();
mapper.writeValue(serialized, test);
String json = serialized.toString();
if ( json.contains("CEST") ) {
System.out.println("It serialized to CET timezone (CEST) [" + serialized.toString() + "]");
}
JacksonTimeZoneTest2 test2 = mapper.readValue(serialized.toString(), JacksonTimeZoneTest2.class);
if ( ! "CET".equals(test2.time.getTimeZone().getID()) ) {
System.out.println("Problem! It deserialized to [" + test2.time.getTimeZone().getID() + "] instead of CET");
}
}
}
当我运行代码时,我得到以下输出:
It serialized to CET timezone (CEST) [{"time":"Mon, 01 Sep 2014 08:00:00 CEST"}]
Problem! It deserialized to [UTC] instead of CET
我还尝试使用JsonFormat注释指定时区,并且我得到了相同的结果。
如果你设置了映射器的时区,它就会工作。
public class JacksonTest {
public Calendar time;
public static void main(String[] args) throws java.io.IOException {
JacksonTest obj = new JacksonTest();
obj.time = new java.util.GregorianCalendar(2014, Calendar.SEPTEMBER, 1);
SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
// Can even remove the sdf TimeZone...
//sdf.setTimeZone(TimeZone.getTimeZone("CET"));
ObjectMapper mapper = new ObjectMapper();
mapper.setDateFormat(sdf);
mapper.setTimeZone(TimeZone.getTimeZone("CET"));
ByteArrayOutputStream serialized = new ByteArrayOutputStream();
mapper.writeValue(serialized, obj);
JacksonTest obj2 = mapper.readValue(serialized.toString(), JacksonTest.class);
System.out.println(serialized);
//{"time":"Mon, 01 Sep 2014 09:00:00 CEST"}
System.out.println(obj2.time.getTimeZone().getID());
//CET
}
}
但我想这并不能回答你的问题,为什么反序列化器忽略日历的时区,而序列化器保持它完整。