当前位置: 移动技术网 > IT编程>开发语言>Java > spring boot @ResponseBody转换JSON 时 Date 类型处理方法,Jackson和FastJson两种方式。

spring boot @ResponseBody转换JSON 时 Date 类型处理方法,Jackson和FastJson两种方式。

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

spring boot @responsebody转换json 时 date 类型处理方法 ,这里一共有两种不同解析方式(jackson和fastjson两种方式,springboot我用的1.x的版本)

第一种方式:默认的json处理是 jackson 也就是对configuremessageconverters 没做配置时

  mybatis数据查询返回的时间,是一串数字,如何转化成时间。两种方法,推荐第一种

  方法一:

  可以在apllication.property加入下面配置就可以

  #时间戳统一转换
  spring.jackson.date-format=yyyy-mm-dd hh:mm:ss

  spring.jackson.time-zone=gmt+8

 

  方法二:

  @jsonformat(timezone = "gmt+8", pattern = "yyyymmddhhmmss")

  private date createtime;

 

第二种方式:当configuremessageconverters 配置为fasjson处理时;

  方法一:全局配置:    fastjsonconfig.setdateformat("yyyy-mm-dd hh:mm:ss");

@configuration
public class webmvcconfig extends webmvcconfigureradapter {

@override
    public void configuremessageconverters(list<httpmessageconverter<?>> converters) {
        super.configuremessageconverters(converters);

        fastjsonhttpmessageconverter fastconverter = new fastjsonhttpmessageconverter();

        fastjsonconfig fastjsonconfig = new fastjsonconfig();
        fastjsonconfig.setserializerfeatures(
                serializerfeature.writenulllistasempty,
                serializerfeature.writemapnullvalue,
                serializerfeature.writenullstringasempty
        );

       //此处是全局处理方式
        fastjsonconfig.setdateformat("yyyy-mm-dd hh:mm:ss");

        fastconverter.setfastjsonconfig(fastjsonconfig);

        list<mediatype> supportedmediatypes = new arraylist<mediatype>();
        supportedmediatypes.add(mediatype.all); // 全部格式
        fastconverter.setsupportedmediatypes(supportedmediatypes);
        converters.add(fastconverter);
    }    
}

  

  方法二:在所需要的字段上配置(比较灵活的方式,根据不同需求转换):

  @jsonfield(format="yyyymmdd")

  private date createtime;

说明:这里如果字段和全局都配置了 ,最后是以全局转换

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网