spring boot @responsebody轉換json 時 date 類型處理方法【兩種方法】,jackson和fastjson兩種方式。
spring boot @responsebody轉換json 時 date 類型處理方法 ,這里一共有兩種不同解析方式(jackson和fastjson兩種方式)
第一種方式:默認的json處理是 jackson 也就是對configuremessageconverters 沒做配置時
mybatis數據查詢返回的時間,是一串數字,如何轉化成時間。兩種方法,推薦第一種
方法一:
可以在apllication.property加入下面配置就可以
1
2
3
|
#時間戳統一轉換 spring.jackson.date-format=yyyy-mm-dd hh:mm:ss spring.jackson.time-zone=gmt+ 8 |
方法二:
1
2
|
@jsonformat (timezone = "gmt+8" , pattern = "yyyymmddhhmmss" ) private date createtime; |
第二種方式:當configuremessageconverters 配置為fasjson處理時;
方法一:全局配置: fastjsonconfig.setdateformat("yyyy-mm-dd hh:mm:ss");
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
@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); } } |
方法二:在所需要的字段上配置(比較靈活的方式,根據不同需求轉換):
1
2
|
@jsonfield (format= "yyyymmdd" ) private date createtime; |
補充:spring boot 將對象轉換為json返回
spring boot默認使用jackson將對象轉換為json,需要配置以下依賴:
1
2
3
|
compile group: 'com.fasterxml.jackson.core' , name: 'jackson-core' , version: '2.9.4' compile group: 'com.fasterxml.jackson.core' , name: 'jackson-databind' , version: '2.9.4' compile group: 'com.fasterxml.jackson.core' , name: 'jackson-annotations' , version: '2.9.4' |
特別需要注意的是返回對象所屬的類的所有屬性必須都要有getter和setter方法。
lombok可以省略getter和setter的書寫,首先得引入依賴:
1
|
compile group: 'org.projectlombok' , name: 'lombok' , version: '1.16.20' |
然后:
1
2
|
@lombok .getter @lombok .setter private long id; @lombok .getter @lombok .setter private string name; |
總結
以上所述是小編給大家介紹的spring boot @responsebody轉換json 時 date 類型處理方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:https://www.cnblogs.com/liran123/p/9516573.html