我试图弄清楚如何使用特定时区序列化和反序列化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注释,我得到了相同的结果。我将其记录为an issue against Jackson。
答案 0 :(得分:1)
如果您设置了映射器的时区,它就可以工作。
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
}
}
但我想这并没有回答你的问题,为什么反序列化器会忽略日历的时区,而序列化程序会保持完整。