当前位置: 移动技术网 > IT编程>开发语言>Java > springmvc fastjson 反序列化时间格式化方法(推荐)

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

2019年07月22日  | 移动技术网IT编程  | 我要评论

沧缘亭,马云进军美国遇对手,调频接收机

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

@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 反序列化时间格式化方法(推荐)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网