问题描述
我有一个来自 API 的日期格式,如下所示:
"start_time": "2015-10-1 3:00 PM GMT+1:00"
这是 YYYY-DD-MM HH:MM am/pm GMT 时间戳.我正在将此值映射到 POJO 中的 Date 变量.显然,它显示了转换错误.
我想知道两件事:
- 我需要使用什么格式来与 Jackson 进行转换?日期是一个很好的字段类型吗?
- 一般来说,有没有办法在变量被 Jackson 映射到对象成员之前对其进行处理?例如,更改格式、计算等.
Date
是一个很好的字段类型.您可以使用 ObjectMapper.setDateFormat
轻松地使 JSON 可解析:
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm a z");myObjectMapper.setDateFormat(df);
一般来说,有没有办法在变量被 Jackson 映射到对象成员之前对其进行处理?诸如更改格式、计算等.
是的.您有几个选择,包括实现自定义 JsonDeserializer
,例如扩展 JsonDeserializer
.这是一个好的开始.
I have a Date format coming from API like this:
"start_time": "2015-10-1 3:00 PM GMT+1:00"
Which is YYYY-DD-MM HH:MM am/pm GMT timestamp.I am mapping this value to a Date variable in POJO. Obviously, its showing conversion error.
I would like to know 2 things:
- What is the formatting I need to use to carry out conversion with Jackson? Is Date a good field type for this?
- In general, is there a way to process the variables before they get mapped to Object members by Jackson? Something like, changing the format, calculations, etc.
Date
is a fine field type for this. You can make the JSON parse-able pretty easily by using ObjectMapper.setDateFormat
:
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm a z");
myObjectMapper.setDateFormat(df);
Yes. You have a few options, including implementing a custom JsonDeserializer
, e.g. extending JsonDeserializer<Date>
. This is a good start.
这篇关于日期格式映射到 JSON Jackson的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!