`
sunbin
  • 浏览: 349756 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

springmvc 接收Date类型的json数据

 
阅读更多

springmvc 接收Date类型的json数据数据时,因为接收的字符串格式无法转换为日期类型所有需要对转入的日期做相应的配置


 

  public class DateStuff {
    @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd,HH:00", timezone="CET")
    public Date creationTime;
  }

 

 

文档参考:http://wiki.fasterxml.com/JacksonFAQDateHandling

----------------------------------------------------------

Jackson FAQ: Date Handling

Handling dates on Java platform is complex business. Jackson tries not to make it any harder than it has to be. Here's how.

 

Basics

All time objects that have associated TimeZone (java.util.Calendar etc) that Jackson constructs use the standard timezone (GMT), not the local time zone (whatever that might be). That is: Jackson defaults to using GMT for all processing unless specifically told otherwise.

 

Date Serialization

Why do Dates get written as numbers?

Default serializer for java.util.Date (and related, such as java.util.Calendar) serialize them using the most efficient accurate representation, so-called epoch timestamp (number of milliseconds since January 1st, 1970, UTC). Assumption is that if user does not care, we should use efficient and accurate representation to get job bdone.

One exception is java.sql.Date, which will always be represent in textual form (but note: use of java.sql.Date is strongly discouraged due to multiple issues, see below for more details)

But I don't like that, I prefer more readable notation

No problem. The simplest way to produce textual serialization is to use:

objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);

which disable use of timestamps (numbers), and instead use a [ISO-8601 ]-compliant notation, which gets output as something like: "1970-01-01T00:00:00.000+0000".

That format sucks, can I use my own?

If you must. You can configure formatting by passing a java.text.DateFormat instance like so:

  objectMapper.setDateFormat(myDateFormat); // 1.8 and above
  objectMapper.getSerializationConfig().setDateFormat(myDateFormat); // for earlier versions (deprecated for 1.8+)

How come this time is off by 9 hours? (5 hours, 3 hours etc)

You may be thinking in terms of your local time zone. Remember that Jackson defaults to using GMT (Greenwich time, one hour behind central European timezone; multiple hours ahead of US time zones).

Can I configure it on per-property basis?

Yes, with Jackson 2.0 you can use the new @JsonFormat annotation:

 

  public class DateStuff {
    @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd,HH:00", timezone="CET")
    public Date creationTime;
  }

 

Notes on java.sql.Date

(aka "Please do NOT use java.sql.Date, ever!")

Although Jackson supports java.sql.Date, there are known issues with respect to timezone handling, partly due to design of this class. It is recommended that this type is avoided, if possible, and regular java.util.Date (or java.util.Calendar) used instead. If this is not possible, it may be necessary for applications to convert these dates using java.util.Calendar and explicit timezone definition.

 

Date Deserialization

Which date formats are supported by default?

RFC-1123, ISO-8601 (or rather, commonly used subset). Also, numeric (integer) serializations are recognized, assumed to be in Unix timestamp notation (milliseconds since epoch, Jan 1st 1970 GMT)

Can this be configured?

Yes: similar to serialization configuration, you can call:

objectMapper.getDeserializationConfig().setDateFormat(myDateFormat);

 

Interoperability

 

Joda Time

Starting with version 1.4, Jackson offers some support for Joda Time data types: basically, its DateTime can be automatically serialized/deserialized similar to how java.util.Date is handled. More support can be added based on user requests.

With version 2.0, support for Joda date/time types was moved to a new module, Jackson-datatype-Joda, to reduce dependencies core databind has, as well as to make it easier to update Joda-specific functionality. To use the module, you will need to add the dependency (via Maven, or by including module jar), and register module; this will add full support similar to how Jackson 1.x works.

 

Known Issues

 

  • Handling of date types when used as java.util.Map keys does not follow above guidelines: rather, a simple call is made to toString() method of Key value on serialization; and on deserialization side, set of types supported out-of-box is limited and does not include any Date types. This should be fixed in future Jackson versions (in 1.9 or later)

分享到:
评论

相关推荐

    springMVC 实战指南

    SpringMVC支持多种数据格式,例如JSON、XML等,通过HttpMessageConverter接口实现不同类型的消息转换。数据格式化是指将数据从一种形式转换成另一种形式,例如从日期字符串转换成Date对象。数据校验是保证数据有效性...

    SpringMVC课堂笔记(2)

    对于简单数据类型(如整型、字符串、日期),只要参数名匹配,SpringMVC会自动进行绑定。若参数名不一致,可以使用@RequestParam来指定。对于POJO类型,只要请求参数名与POJO属性名一致,SpringMVC会自动将请求参数...

    分享SpringMVC归纳

    - 使用`@ResponseBody`注解将Java对象转换为JSON数据。 ```java @RequestMapping(value = "/items", method = RequestMethod.POST) public @ResponseBody Item addItem(@RequestBody Item newItem) { // 业务...

    SpringMVC 学习总结

    #### 处理JSON数据 SpringMVC 自带了对 JSON 数据的支持,无需额外引入第三方库即可处理 JSON 数据: - **接收 JSON 数据:** 可以直接将 JSON 数据绑定到 POJO 对象中。 ```java @RequestMapping(value = "/...

    html5+jquery与ssm进行json交互集成项目

    前端接收到JSON数据后,通过jQuery解析并更新DOM,完成页面的动态展示。 项目结构通常包含以下部分: 1. **src/main/java**:存放Java源代码,包括Spring配置、控制器、服务接口和服务实现、DAO类等。 2. **src/...

    spring mvc 接口

    ### Spring MVC 接口返回 JSON 数据详解 #### 一、Spring MVC 概念与作用 Spring MVC 是 Spring Framework 的一个重要模块,它实现了 MVC(模型-视图-控制器)设计模式,帮助开发者构建易于维护和扩展的 Web 应用...

    springmvc01_java_maven_idea_

    这个教程“springmvc01_java_maven_idea_”显然聚焦于使用Maven构建工具、IntelliJ IDEA集成开发环境(IDE)以及Spring MVC的参数处理和日期格式转换。下面将详细解释这些知识点。 1. **Spring MVC基础**: Spring...

    Spring MVC请求参数接收的全面总结教程

    Spring MVC请求参数接收其实一般的表单或者JSON数据的请求都是相对简单的,一些复杂的处理主要包括URL路径参数、文件上传、数组或者列表类型数据等。另外,关于参数类型中存在日期类型属性(例如java.util.Date、...

    springmvc fastjson 反序列化时间格式化方法(推荐)

    接下来,在Spring MVC的配置文件(如`springMVC.xml`)中,替换原来的`FastJsonHttpMessageConverter`实例为我们的自定义类`JsonHttpMessageConverter`,并设置支持的媒体类型及序列化特性: ```xml <!-- 替换...

    Spring MVC自定义日期类型转换器实例详解

    这个接口是json-lib框架提供的接口,用于自定义JSON数据的处理方式。 2. 设置日期格式:转换器中定义了一个String类型的变量format,用来指定日期格式化的模板。在这个例子中,它被设置为"yyyy-MM-dd",符合大多数...

    datatables render与日期转换(moment.js)

    在`SpringMVC_datatables_moment` 这个项目中,很可能使用Spring MVC作为后端框架,提供JSON数据给前端的DataTables。在Spring MVC中,你可以将日期转换为符合JSON标准的格式,如ISO 8601,然后在前端使用`moment.js...

    自整理Java关于基础和框架的面试题

    ##### java的基本数据类型 - 整型:byte、short、int、long - 浮点型:float、double - 字符型:char - 布尔型:boolean ##### 冒泡排序 - **算法思想**:比较相邻元素,将较大的元素往后移动。 ##### 二分查找法 ...

    java面试知识

    ##### java的基本数据类型 - **整型**:byte、short、int、long - **浮点型**:float、double - **字符型**:char - **布尔型**:boolean ##### 冒泡排序 - **算法**:比较相邻元素,如果第一个比第二个大,就...

    Bootstrap Search Suggest使用例子

    例如,根据上述配置,接口可能是 `/user/getuserName`,它应该接收一个查询参数(例如:`d`),然后返回一个包含用户名称的JSON数组,如: ```json [ {"userName": "张三"}, {"userName": "李四"}, {"userName":...

Global site tag (gtag.js) - Google Analytics