我试图弄清楚如何序列化和反序列化具有特定时区的日历对象。我认为 jackson 可以尊重我的时区并允许我将我的日历实例保留在指定的时区,这是合理的。它适用于序列化,但不适用于反序列化。我做错了什么?
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 .
最佳答案
如果您设置映射器的时区,它就会起作用。
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
}
}
但我想这并不能回答您的问题,即为什么解串器会忽略日历的时区,而序列化器会保持其完整。
关于java - 如何使用 Jackson 获取特定时区的日历?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39598419/