如何使用杰克逊反序列化JS日期? [英] How to deserialize JS date using Jackson?

查看:213
本文介绍了如何使用杰克逊反序列化JS日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从ExtJS获取一个日期字符串,格式如下:


2011-04-08T09:00:00 / p>

当我尝试反序列化这个日期时,它将时区改为印度标准时间(当时增加+5:30)。这是我反序列化日期的方式:

  SimpleDateFormat dateFormat = new SimpleDateFormat(yyyy-MM-dd'THH :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);

如何以时区的方式反序列出日期呢? / p>

解决方案

我发现了一个工作,但是我需要在整个项目中注释每个日期的设置器。有没有办法在创建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)


I'm getting a date string from ExtJS in the format:

"2011-04-08T09:00:00"

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);

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?

解决方案

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?

Here's what I did:

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);
        }

    }

}

And annotated each Date field's setter method with this:

@JsonDeserialize(using = CustomJsonDateDeserializer.class)

这篇关于如何使用杰克逊反序列化JS日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆