SpringMVC @RequestBody Date类型的Json转换方式

目录
  • SpringMVC @RequestBody Date类型的Json转换
    • 通过GsonBuilder设置DateFormat的格式
    • 以零配置框架为例
    • 以零配置形式框架下的代码实现为例讲解
  • @RequestBody接收json字符串,自动将日期字符串转换为java.util.Date
    • 1.配置springMVC可以接收json字符串
    • 2.@Controller类代码
    • 3.实体类对象代码
    • 4.DateJsonSerializer类代码
    • 5.DateJsonDeserializer类代码

SpringMVC @RequestBody Date类型的Json转换

正常使用Json或Gson对Date类型序列化成字符串时,得到的是类似”Dec 5, 2017 8:03:34 PM”这种形式的字符串,前端得到了这种格式的很难明白这个具体是什么时间,可读性很低。

同时如果用这种形式的字符串来反序列化为Date对象,也会失败,这个过程是不可逆的。如何将Date对象序列化为指定格式的字符串,比如”yyyy-MM-dd”格式的字符串,以Gson的使用为例来说明。

对于Gson对象,可以使用GsonBuilder来实例化

通过GsonBuilder设置DateFormat的格式

Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();

经过这样设置后,使用toJson(Object obj)方法对Date对象序列化时,会输出”yyyy-MM-dd HH:mm:ss”格式的字符串;

也可以将”yyyy-MM-dd HH:mm:ss”格式的字符串反序列化为一个Date对象。值得注意的是,当一个Date对象未指定”HH:mm:ss”时,会使用当前时间来填充以补齐格式长度。

以上讲的是Date对象的序列化和反序列化为字符串的方法,在SpingMVC框架中并不适用,下面讲SpringMVC中Date的序列化和反序列化。

SpringMVC中,如果前端以GET的形式传递字符串,后端想将此字符串反序列化为Date对象,最常用的就是注册Formatter对象

以零配置框架为例

public class String2DateFormatter implements Formatter<Date> {
    private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    private static final String DATE_FORMAT = "yyyy-MM-dd";
    @Override
    public String print(Date object, Locale locale) {
        return new GsonBuilder().setDateFormat(DATE_TIME_FORMAT).create().toJson(object);
    }
    @Override
    public Date parse(String text, Locale locale) throws ParseException {
        if (text.length() > 10) {
            return new SimpleDateFormat(DATE_TIME_FORMAT).parse(text);
        } else {
            return new SimpleDateFormat(DATE_FORMAT).parse(text);
        }
    }
}
public class MvcContextConfig extends WebMvcConfigurerAdapter {
    ......
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addFormatter(new String2DateFormatter());
    }
    ......
}

当然也可以用配置文件的形式配置,具体方法请百度。

当前端传递字符串,Controller用Date类型的参数接受时,会使用Formatter将字符串反序列化为Date对象。

如果前端以POST形式传递一个Json对象,对象内部有一个Date属性,前端传递的是字符串,后端用一个标识@RequestBody的复合对象接收时,Formatter是不会起作用的。

此时起作用的是HttpMessageConverter的实现类。正常情况下项目内有Jackson或Gson依赖,能够将Json反序列化为复合对象。

如果依赖了Jackson,且使用Jackson的HttpMessageConverter反序列化Json,那么仅支持反序列化简单数据类型的属性,不支持Date类型;但是如果是Gson类型,是支持”yyyy-MM-dd HH:mm:ss”格式的反序列化的,确定不支持”yyyy-MM-dd”格式,其他格式不确定。

也就是说依赖Gson可以将前端的”yyyy-MM-dd HH:mm:ss”格式的字符串反序列化为Date对象,但是将Date对象返回给前端时,解析得到的还是类似”Dec 5, 2017 8:03:34 PM”这种形式的字符串,并不可取。

当我们使用Jackson作为Json对象的序列化和反序列化的解析器时

以零配置形式框架下的代码实现为例讲解

public class MvcContextConfig extends WebMvcConfigurerAdapter {
    ......
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        StringHttpMessageConverter stringConverter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
        stringConverter.setWriteAcceptCharset(false);
        converters.add(stringConverter);
        converters.add(new ByteArrayHttpMessageConverter());
        converters.add(new ResourceHttpMessageConverter());
        converters.add(new MappingJackson2XmlHttpMessageConverter());
        //设置Date类型使用HttpMessageConverter转换后的格式,或者注册一个GsonHttpMessageConverter,能直接支持字符串到日期的转换
        //当指定了日期字符串格式后,如果传的日志格式不符合,则会解析错误
        converters.add(new MappingJackson2HttpMessageConverter(
            new ObjectMapper().setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))));
        //GsonHttpMessageConverter不支持yyyy-MM-dd形式的字符串转换为日期
        //converters.add(new GsonHttpMessageConverter());
    }
    ......
}

当我们选择使用Jackson作为Json的解析器时,需要注册一个MappingJackson2HttpMessageConverter,对内部默认的objectMapper对象做一个拓展,需要指定日期格式化器,当我们指定了具体的格式时,只支持这种格式的转换,其他的格式转换时会报错。

因此需要前端在传递日期字符串时,加上默认的时间,比如”2017-12-2 00:00:00”,虽然多了点工作,但是能确保格式转换的正确。

当然并不是一定要”yyyy-MM-dd HH:mm:ss”,其他的格式也都支持的,比如”yyyy-MM-dd”等等,具体可以看项目需求自定义,前端传递日期字符串的格式需要符合自定义的格式。

当配置了DateFormat时,传递对象给前端,对象内部有Date属性,也会将其序列化为这个格式的字符串。

XML文件形式配置HttpMessageConverter的方法可自行百度。

@RequestBody接收json字符串,自动将日期字符串转换为java.util.Date

1.配置springMVC可以接收json字符串

<?xml version="1.0" encoding="UTF-8"?>
<beans
 xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:p="http://www.springframework.org/schema/p"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-3.1.xsd
 http://www.springframework.org/schema/tx
 http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
 http://www.springframework.org/schema/aop
 http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
 http://www.springframework.org/schema/mvc
 http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
 <!-- 解决@ResponseBody返回中文乱码,解决@RequestBody接收Json字符串自动转换为实体、List、Map格式转换器 -->
 <bean
  class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
  <property name="messageConverters">
   <list>
    <!--
    <bean
     class="org.springframework.http.converter.StringHttpMessageConverter">
     <property name="supportedMediaTypes">
      <list>
       <value>text/html;charset=UTF-8</value>
      </list>
     </property>
    </bean>
    -->
    <bean
     class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
     <property name="supportedMediaTypes">
      <list>
       <value>application/json;charset=UTF-8</value>
      </list>
     </property>
    </bean>
   </list>
  </property>
 </bean>
 <!-- 扫描包,应用Spring的注解 -->
 <context:component-scan base-package="com.mvc.action"></context:component-scan>
 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
  p:viewClass="org.springframework.web.servlet.view.JstlView"
  p:prefix="/"
  p:suffix=".jsp">
 </bean>
 <!-- SpringMVC自定义拦截器,使SpringMVC开启CORS支持 -->
 <!--
 <mvc:interceptors>
  <mvc:interceptor>
   <mvc:mapping path="/*"/>
   <bean class="com.mvc.dao.CorsInterceptor"></bean>
  </mvc:interceptor>
 </mvc:interceptors>
 -->
 <context:annotation-config/>
 <mvc:annotation-driven/>
</beans>

2.@Controller类代码

@RequestMapping(value="/addDicAppUsers.do")
 @ResponseBody
 public boolean addDicAppUsers(@RequestBody DicAppUsersModel dicAppUsersModel)
 {
  if(dicAppUsersService.addDicAppUsers(dicAppUsersModel))
  {
   return true;
  }
  else
  {
   return false;
  }
 }

3.实体类对象代码

package com.mvc.model;
import java.util.Date;
import org.codehaus.jackson.map.annotate.JsonDeserialize;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import com.mvc.imp.DateJsonDeserializer;
import com.mvc.imp.DateJsonSerializer;

/**
 * 用户视图类
 * @author suyunlong
 *
 */
@SuppressWarnings("serial")
public class DicAppUsersModel implements java.io.Serializable
{
 private long id;
 private String loginid;
 private String loginname;
 private String loginpassword;
 private String loginunitcode;
 private String workplace;
 @JsonSerialize(using=DateJsonSerializer.class)
 @JsonDeserialize(using=DateJsonDeserializer.class)
 private Date addtime;
 private long sourceid;
 @JsonSerialize(using=DateJsonSerializer.class)
 @JsonDeserialize(using=DateJsonDeserializer.class)
 private Date createdate;
 public DicAppUsersModel() {
  super();
 }
 public DicAppUsersModel(long id, String loginid, String loginname,
   String loginpassword, String loginunitcode, String workplace,
   Date addtime, long sourceid, Date createdate) {
  super();
  this.id = id;
  this.loginid = loginid;
  this.loginname = loginname;
  this.loginpassword = loginpassword;
  this.loginunitcode = loginunitcode;
  this.workplace = workplace;
  this.addtime = addtime;
  this.sourceid = sourceid;
  this.createdate = createdate;
 }
 public long getId() {
  return id;
 }
 public void setId(long id) {
  this.id = id;
 }
 public String getLoginid() {
  return loginid;
 }
 public void setLoginid(String loginid) {
  this.loginid = loginid;
 }
 public String getLoginname() {
  return loginname;
 }
 public void setLoginname(String loginname) {
  this.loginname = loginname;
 }
 public String getLoginpassword() {
  return loginpassword;
 }
 public void setLoginpassword(String loginpassword) {
  this.loginpassword = loginpassword;
 }
 public String getLoginunitcode() {
  return loginunitcode;
 }
 public void setLoginunitcode(String loginunitcode) {
  this.loginunitcode = loginunitcode;
 }
 public String getWorkplace() {
  return workplace;
 }
 public void setWorkplace(String workplace) {
  this.workplace = workplace;
 }
 public Date getAddtime() {
  return addtime;
 }
 public void setAddtime(Date addtime) {
  this.addtime = addtime;
 }
 public long getSourceid() {
  return sourceid;
 }
 public void setSourceid(long sourceid) {
  this.sourceid = sourceid;
 }
 public Date getCreatedate() {
  return createdate;
 }
 public void setCreatedate(Date createdate) {
  this.createdate = createdate;
 }
}

4.DateJsonSerializer类代码

package com.mvc.imp;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;

public class DateJsonSerializer extends JsonSerializer<Date>
{
 public static final SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 public void serialize(Date date,JsonGenerator jsonGenerator,SerializerProvider serializerProvider)
   throws IOException,JsonProcessingException
 {
  jsonGenerator.writeString(format.format(date));
    }
}

5.DateJsonDeserializer类代码

package com.mvc.imp;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.JsonDeserializer;

public class DateJsonDeserializer extends JsonDeserializer<Date>
{
 public static final SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 public Date deserialize(JsonParser jsonParser,DeserializationContext deserializationContext)
   throws IOException,JsonProcessingException
 {
  try
  {
   return format.parse(jsonParser.getText());
  }
  catch(Exception e)
  {
   System.out.println(e.getMessage());
   throw new RuntimeException(e);
  }
 }
}

这样,就可以把接收到的json日期字符串转换为Date了。后面,就可以直接通过Date类型保存日期数据了。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • 详解SpringMVC @RequestBody接收Json对象字符串

    页面提交请求参数有两种,一种是form格式提交,一种json格式提交 通常情况下我们使用的都是form格式提交的数据,数据格式:k=v&k=v,这个时候用springMVC接收参数没有问题,但有时候前端会通过json向后端传递数据,就会出现springMVC获取不到参数值的情况 注意:jQuery的$.post方法虽然也可以传递json格式数据,但实际上是用的form格式提交,jquery会帮你把json转成form格式提交后台 所以其实可以通过$.post,$.get来提交json格式,让jq

  • spring boot @ResponseBody转换JSON 时 Date 类型处理方法【两种方法】

    spring boot @ResponseBody转换JSON 时 Date 类型处理方法[两种方法],Jackson和FastJson两种方式. spring boot @ResponseBody转换JSON 时 Date 类型处理方法 ,这里一共有两种不同解析方式(Jackson和FastJson两种方式) 第一种方式:默认的json处理是 jackson 也就是对configureMessageConverters 没做配置时 mybatis数据查询返回的时间,是一串数字,如何转化成时间.

  • 详解spring mvc4使用及json 日期转换解决方案

    又到搭新开发环境的时候,总是不免去网上搜下目前最新的框架.spring是web开发必用的框架,于是乎下载了目前最新的spring4.0.3,同时越来越不想用struts2,想试试spring mvc,也将spring-webmvc4.0.3下了下来,投入两天时间学习后,发现还是挺优雅的,特别是从3.0后,spring mvc使用注解方式配制,以及对rest风格的支持,真是完美致极. 下面将这两天研究到的问题做个总结,供参考. 1.request对象的获取 方式1:在controller方法上加入

  • springmvc实现json交互-requestBody和responseBody

    json数据交互 1.为什么要进行json数据交互 json数据格式在接口调用中.html页面中较常用,json格式比较简单,解析还比较方便. 比如:webservice接口,传输json数据. 2.springmvc进行json交互 (1)请求json.输出json,要求请求的是json串,所以在前端页面中需要将请求的内容转成json,不太方便. (2)请求key/value.输出json.此方法比较常用. 3.环境准备 3.1加载json转的jar包 springmvc中使用jackson的

  • SpringMVC restful 注解之@RequestBody进行json与object转换

    由于快过年的原因,项目组没有太多任务,闲来无事研究了一下spring中restful调用.发现spring竟然已经强大到如此境界,程序员已经不需要在关心在写接口的过程中数据的转换以及调用,只需要专注业务.下面我总结一下步骤及其在研究过程的遇到的问题. 步骤: 1.git clone https://github.com/spring-guides/gs-rest-service.git 从spring官网上下载了源码 2.进行maven编译(gradle也行) 3.运行.访问http://loc

  • SpringMVC @RequestBody Date类型的Json转换方式

    目录 SpringMVC @RequestBody Date类型的Json转换 通过GsonBuilder设置DateFormat的格式 以零配置框架为例 以零配置形式框架下的代码实现为例讲解 @RequestBody接收json字符串,自动将日期字符串转换为java.util.Date 1.配置springMVC可以接收json字符串 2.@Controller类代码 3.实体类对象代码 4.DateJsonSerializer类代码 5.DateJsonDeserializer类代码 Spr

  • springboot前端传参date类型后台处理的方式

    目录 springboot前端传参date类型后台处理 先说结论 解决方法 前端如何发送date类型的参数给后端 首先阐述一下常见的几种时间类型的区别 GET传参时 Post传参时 后端接收请求代码 模拟浏览器请求 springboot前端传参date类型后台处理 先说结论 建议大家直接使用@JsonFormat,原因如下: 1.针对json格式:在配置文件中加以下配置 spring.jackson.date-format=yyyy-MM-dd HH:mm:ss spring.jackson.t

  • SpringMVC对日期类型的转换示例

    在做web开发的时候,页面传入的都是String类型,SpringMVC可以对一些基本的类型进行转换,但是对于日期类的转换可能就需要我们配置. 1.如果查询类使我们自己写,那么在属性前面加上@DateTimeFormat(pattern = "yyyy-MM-dd")  ,即可将String转换为Date类型,如下 @DateTimeFormat(pattern = "yyyy-MM-dd") private Date createTime; 2.如果我们只负责we

  • java Long类型转为String类型的两种方式及区别说明

    目录 java Long类型转为String类型 1.Long.ValueOf("String")返回Long包装类型数据 2.Long.parseLong("String")返回long基本数据类型 Java中Long.String.Date 类型之间的转换 1.Java.util.Date类型转换成long类型 2.long类型转换成java.util.Date类型 3.形如"2015-08-31 21:08:06"等格式化string类型转

  • SpringMVC接收java.util.Date类型数据的2种方式小结

    SpringMVC接收java.util.Date类型数据 在Controller中如下定义方法 public PassQueryRequest trade(@ModelAttribute PassQueryRequest tradeRequest, @RequestParam(value="startDate", required=true)Date startDate, @RequestParam(value="endDate", required=true)D

  • Json对象和字符串互相转换json数据拼接和JSON使用方式详细介绍(小结)

    JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.它基于ECMAScript的一个子集. JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C.C++.C#.Java.JavaScript.Perl.Python等).这些特性使JSON成为理想的数据交换语言. 易于人阅读和编写,同时也易于机器解析和生成(一般用于提升网络传输速率). 一.JSON字符串转换为JSON对象: eval() 和 JSON.parse eg- js

  • springMvc 前端用json的方式向后台传递对象数组方法

    如下所示: JSP var vipFee= new Array; //遍历选中的对象 $("#feeList :checkbox:checked").each(function(i){ vipFee.push({"enterpriseSeq":$(this).attr("enterpriseSeq"),"merchNo":$(this).val(),"serviceFee":$(this).attr(&qu

  • mybatis中string和date的转换方式

    实体里用的java.util.date,数据库用的是datetime,页面是字符串<input type="date">.将页面标签<input type="date">的内容添加到数据库 实体 public class BaseInformation { //信息主键 private String id; //信息标题 private String title; //信息类型id(需要在数据字典定义) private String type

  • MySQL读取JSON转换的方式

    目录 存储 存在什么问题? 如何处理 存储 mysql5.7+开始支持存储JSON,后续不断优化,应用也越来越广泛 你可以自己将数据转换成Json String后插入,也可以选择使用工具, 而mybatis-plus就为此提供了非常简便的方式, 只需要在字段上加上 @TableField(typeHandler = XxxTypeHandler.class), mybatis-plus就会自动帮你做转换,通用一般就两个: - com.baomidou.mybatisplus.extension.

随机推荐