日期格式映射到 JSON Jackson [英] Date format Mapping to JSON Jackson

查看:29
本文介绍了日期格式映射到 JSON Jackson的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个来自 API 的日期格式,如下所示:

"start_time": "2015-10-1 3:00 PM GMT+1:00"

这是 YYYY-DD-MM HH:MM am/pm GMT 时间戳.我正在将此值映射到 POJO 中的 Date 变量.显然,它显示了转换错误.

我想知道两件事:

  1. 我需要使用什么格式来与 Jackson 进行转换?日期是一个很好的字段类型吗?
  2. 一般来说,有没有办法在变量被 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:

  1. What is the formatting I need to use to carry out conversion with Jackson? Is Date a good field type for this?
  2. 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.

解决方案

What is the formatting I need to use to carry out conversion with Jackson? Is Date a good field type for this?

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

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.

Yes. You have a few options, including implementing a custom JsonDeserializer, e.g. extending JsonDeserializer<Date>. This is a good start.

这篇关于日期格式映射到 JSON Jackson的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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