如何使用 Jackson 反序列化 JS 日期? [英] How to deserialize JS date using Jackson?
问题描述
我从 ExtJS 得到一个日期字符串,格式为:
I'm getting a date string from ExtJS in the format:
2011-04-08T09:00:00"
"2011-04-08T09:00:00"
当我尝试反序列化这个日期时,它会将时区更改为印度标准时间(时间增加 +5:30).这就是我反序列化日期的方式:
when i try to deserialize this date, it changes the timezone to Indian Standard Time (adds +5:30 to the time) . This is how i'm deserializing the date:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
getObjectMapper().getDeserializationConfig().setDateFormat(dateFormat);
这样做也不会改变时区.我仍然在 IST 中得到日期:
Doing this also doesn't change the timezone. I still get the date in IST:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
getObjectMapper().getDeserializationConfig().setDateFormat(dateFormat);
如何在没有时区麻烦的情况下以日期的方式反序列化日期?
How do I deserialize the date in the way in which it is coming without the hassles of Timezone?
推荐答案
我找到了一个变通方法,但是我需要在整个项目中注释每个日期的 setter.有没有办法在创建 ObjectMapper 时指定格式?
I found a work around but with this I'll need to annotate each date's setter throughout the project. Is there a way in which I can specify the format while creating the 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 方法:
And annotated each Date field's setter method with this:
@JsonDeserialize(using = CustomJsonDateDeserializer.class)
这篇关于如何使用 Jackson 反序列化 JS 日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!