我从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);
我如何在没有时区的麻烦的情况下反序列化日期?
发布于 2011-04-09 00:48:50
我找到了一个解决办法,但我需要在整个项目中注释每个日期的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);
}
}
}
并使用下面的代码注释每个日期字段的setter方法:
@JsonDeserialize(using = CustomJsonDateDeserializer.class)
发布于 2012-08-31 23:58:46
这对我很有效--我使用的是jackson 2.0.4
ObjectMapper objectMapper = new ObjectMapper();
final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
objectMapper.setDateFormat(df);
发布于 2016-09-15 02:44:08
关于这个话题有一个很好的博客:http://www.baeldung.com/jackson-serialize-dates使用@JsonFormat看起来是最简单的方式。
public class Event {
public String name;
@JsonFormat
(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
public Date eventDate;
}
https://stackoverflow.com/questions/5591967
复制相似问题