广告
返回顶部
首页 > 资讯 > 后端开发 > Python >SpringMVC @RequestBody Date类型的Json转换方式
  • 569
分享到

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

2024-04-02 19:04:59 569人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

目录springMVC @RequestBody Date类型的JSON转换通过GsonBuilder设置DateFORMat的格式以零配置框架为例以零配置形式框架下的代码实现为例讲

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="
@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类型保存日期数据了。

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

--结束END--

本文标题: SpringMVC @RequestBody Date类型的Json转换方式

本文链接: https://www.lsjlt.com/news/155206.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • SpringMVC @RequestBody Date类型的Json转换方式
    目录SpringMVC @RequestBody Date类型的Json转换通过GsonBuilder设置DateFormat的格式以零配置框架为例以零配置形式框架下的代码实现为例讲...
    99+
    2022-11-12
  • springmvc 获取@Requestbody转换的异常处理方式
    1、引入问题 使用spring 自动的@RequestBody,可以很方便的将参数转换成对象,然而在自动转换中出现如果出现异常,会默认直接发送HTTP异常代码和错误信息,如何才能自定...
    99+
    2022-11-12
  • go 类型转换方式(interface 类型的转换)
    go 在做类型转换时,报错: cannot convert m (type interface {}) to type Msg: need type assertion 原...
    99+
    2022-06-07
    GO interface 类型转换
  • springmvc 获取@Requestbody转换的异常处理方法
    这篇文章主要介绍“springmvc 获取@Requestbody转换的异常处理方法”,在日常操作中,相信很多人在springmvc 获取@Requestbody转换的异常处理方法问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法...
    99+
    2023-06-20
  • go类型转换及与C的类型转换方式
    GO类型转换及与C的类型转换 类型转换 语法 dst := float32(src) 示例 var num int = 520 f32 := float32(num) i6...
    99+
    2022-06-07
    GO
  • java中Calendar与Date类型互相转换的方法
    下文笔者讲述使用Java代码将Calendar与Date类型互转的方法分享,如下所示:Calendar与Date类型是我们日常开发中常用的两种数据类型, 它们用于不同的场景,两者具有...
    99+
    2022-11-13
  • Long类型毫秒数时间格式转换成Date格式
    前言 请各大网友尊重本人原创知识分享,谨记本人博客:南国以南i、 ...
    99+
    2023-10-03
    java mysql 开发语言
  • SpringMVC修改返回值类型后的消息转换器处理方式
    目录问题案例为什么?了解问题原因及分析解决方法结语o(╯□╰)o这标题看起来有点奇怪,所以先以一个小小的案例来说明一下本文要描述和解决的问题 问题案例 假设有一个Controller...
    99+
    2022-11-12
  • mybatis中string和date的转换方式
    实体里用的java.util.date,数据库用的是datetime,页面是字符串<input type="date">。将页面标签<input type="dat...
    99+
    2022-11-12
  • Python数字类型的转换方式
    这篇文章主要讲解了“Python数字类型的转换方式”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Python数字类型的转换方式”吧! Python 数字数据类型用于存储数值。数据类...
    99+
    2023-06-04
  • C语言隐式类型转换与强制类型转换的方法是什么
    本篇内容主要讲解“C语言隐式类型转换与强制类型转换的方法是什么”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“C语言隐式类型转换与强制类型转换的方法是什么”吧!类型转换数据有不同的类型,不同类型数...
    99+
    2023-06-25
  • MySQL读取JSON转换的方式
    目录存储存在什么问题?如何处理存储 mysql5.7+开始支持存储JSON,后续不断优化,应用也越来越广泛 你可以自己将数据转换成Json String后插入,也可以选择使用工具, ...
    99+
    2022-11-13
  • php json 格式的转换方法
    这篇文章主要为大家展示了php json 格式的转换方法,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带大家一起来研究并学习一下“php json 格式的转换方法”这篇文章吧。JS是什么JS是JavaScript的简称,它是...
    99+
    2023-06-06
  • C++强制类型转换的四种方式
    目录1 C++类型转换本质1.1 自动类型转换(隐式)1.2 强制类型转换(显式)1.3 类型转换的本质1.4 类型转换的安全性2 四种类型转换运算符2.1 C语言的强制类型转换与C...
    99+
    2022-11-13
  • Java之String类型的编码方式转换
    目录String类型的编码方式转换String字符集的编码和解码String编码String解码总结String类型的编码方式转换 在JAVA中,String类型的编码方式转换,St...
    99+
    2023-02-28
    Java String类型 String类型编码 String类型编码转换
  • c#中的类型转换方式有哪些
    在C#中,有以下几种类型转换方式:1. 隐式类型转换:当目标类型的范围大于源类型时,可以进行隐式类型转换。例如,将int类型的值赋给...
    99+
    2023-08-09
    c#
  • springboot:接收date类型的参数方式
    目录springboot:接收date类型的参数springboot 传递Date等实体参数时候报错springboot:接收date类型的参数 今天有个postmapping方法,...
    99+
    2022-11-12
  • JavaScript类型转换的方法
    这篇文章主要讲解了“JavaScript类型转换的方法”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“JavaScript类型转换的方法”吧!  ...
    99+
    2022-10-19
  • 使用SpringMVC响应json格式返回的结果类型
    背景: SpringMVC如何响应json格式的数据? 技术实现 方式1:在Controller使用@RestController注解 方式2:在Controller使用@Contr...
    99+
    2022-11-12
  • C++强制类型转换的方式有哪些
    本篇内容主要讲解“C++强制类型转换的方式有哪些”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“C++强制类型转换的方式有哪些”吧!1 C++类型转换本质1.1 自动类型转换(隐式)利用编译器内置...
    99+
    2023-06-30
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作