我从 ExtJS 得到一个日期字符串,格式为:
"2011-04-08T09:00:00"
当我尝试反序列化此日期时,它会将时区更改为印度标准时间(时间增加 +5:30)。这就是我反序列化日期的方式:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
getObjectMapper().getDeserializationConfig().setDateFormat(dateFormat);
这样做也不会更改时区。我仍然在 IST 中得到日期:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
getObjectMapper().getDeserializationConfig().setDateFormat(dateFormat);
如何在没有时区麻烦的情况下以日期的方式反序列化日期?
最佳答案
我找到了一个解决方法,但我需要在整个项目中注释每个日期的 setter 。有没有一种方法可以在创建 ObjectMapper 时指定格式?
这就是我所做的:
public class CustomJsonDateDeserializer extends JsonDeserializer<Date>
{
@Override
public Date deserialize(JsonParser jsonParser,
DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
String date = jsonParser.getText();
try {
return format.parse(date);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}
并用这个注释每个 Date 字段的 setter 方法:
@JsonDeserialize(using = CustomJsonDateDeserializer.class)
关于java - 如何使用 Jackson 反序列化 JS 日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5591967/