小编典典

如何使用Jackson来反序列化JS日期?

json

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

如何以无时区麻烦的日期反序列化日期?


阅读 302

收藏
2020-07-27

共1个答案

小编典典

我找到了解决方法,但与此同时,我需要在整个项目中注释每个日期的设置器。有没有一种方法可以在创建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)
2020-07-27