温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-09-20 16:04:09 来源:脚本之家 阅读:852 作者:jingxian 栏目:编程语言

第一种情况是从后台拿到数据,进行反序列化,反序列化格式时间:试了一下很多网上的方法,最后发现还是在实体类上面的日期字段加上如下注解,可以完成格式化操作,否则默认就都是时间戳的格式:

@JSONField (format="yyyy-MM-dd HH:mm:ss") 
public Date birthday; 

@JSONField (format="yyyy-MM-dd HH:mm:ss") 
public Date birthday;

第二种情况是:response返回给前段的时间格式,一开始是时间戳,需要转成想要的格式yyyy-MM-dd重写方法:

package com.jjs.util; 
 
import java.io.IOException; 
 
import org.springframework.http.HttpOutputMessage; 
import org.springframework.http.converter.HttpMessageNotWritableException; 
 
import com.alibaba.fastjson.JSON; 
import com.alibaba.fastjson.serializer.SerializerFeature; 
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; 
 
public class JsonHttpMessageConverter extends FastJsonHttpMessageConverter { 
 
  @Override 
  protected void writeInternal(Object obj, HttpOutputMessage outputMessage) 
      throws IOException, HttpMessageNotWritableException { 
    // TODO Auto-generated method stub 
    JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH"; 
    JSON.toJSONString(obj, SerializerFeature.WriteDateUseDateFormat); 
    super.writeInternal(obj, outputMessage); 
 
  } 
 
} 

然后,将springMVC.xml(具体文件名以项目而定) 的配置修改为如下, 引用重写了writeInternal()方法的类进行json序列化

<mvc:annotation-driven> 
    <mvc:message-converters register-defaults="true"> 
      <!-- <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> --> 
      <bean class="com.jjs.util.JsonHttpMessageConverter"> 
        <property name="supportedMediaTypes"> 
          <list> 
            <value>text/html;charset=UTF-8</value> 
            <value>application/json</value> 
          </list> 
        </property> 
        <property name="features"> 
          <list> 
          <value>WriteDateUseDateFormat</value> 
            <value>WriteMapNullValue</value> 
            <value>QuoteFieldNames</value> 
          </list> 
        </property> 
      </bean> 
    </mvc:message-converters> 
  </mvc:annotation-driven> 

记录一下,方便查看

以上这篇springmvc fastjson 反序列化时间格式化方法(推荐)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI