SpringBoot整合Gson 整合Fastjson的实例详解
SpringBoot整合Gson整合Fastjson
一、SpringBoot整合Gson
1、pom依赖
#在SpringBoot中给我们自带了json解析器,我们需要移除SpringBoot自带的jackson,在添加Gson依赖
org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-json com.google.code.gson gson org.springframework.boot spring-boot-starter-test test
2、User实体
/** *@Create_Authormsfh *@Create_Date2020-11-2515:54:15 *@DescriptionUser实体 */ publicclassUser{ privateIntegerid; privateStringname; privateDatebirthday; @Override publicStringtoString(){ return"User{"+ "id="+id+ ",name='"+name+'\''+ ",birthday="+birthday+ '}'; } /**省略set&get**/ }
3、UserController
/** *@Create_Authormsfh *@Create_Date2020-11-2515:55:15 *@DescriptionUserController控制器 */ @RestController publicclassUserController{ @GetMapping("/user") publicListgetUsers(){ ArrayList users=newArrayList<>(); for(inti=0;i<10;i++){ Useruser=newUser(); user.setId(i); user.setName("msfh-->"+i); user.setBirthday(newDate()); users.add(user); } returnusers; } }
4、WebMvcConfig
#在之前的一篇博客中有介绍,大家不太明白可以先看一下上一篇博客,这次就不放测试的结果了! #在GsonHttpMessageConvertersConfiguration中含有GsonHttpMessageConverter #在GsonAutoConfiguration中含有Gson #我们可以分别写两个bean去实现gson的配置(GsonHttpMessageConverter或Gson) #建议大家没事的话,可以看下源码
/** *@Create_Authormsfh *@Create_Date2020-11-2516:05:56 *@DescriptionWebMvcConfig配置类 */ @Configuration publicclassWebMvcConfig{ //@Bean //GsonHttpMessageConvertergsonHttpMessageConverter(){ //GsonHttpMessageConverterconverter=newGsonHttpMessageConverter(); //converter.setGson(newGsonBuilder().setDateFormat("yyyy-MM-dd").create()); //returnconverter; //} @Bean Gsongson(){ returnnewGsonBuilder().setDateFormat("yyyy-MM-dd").create(); } }
二、SpringBoot整合FastJson
1、pom依赖
#这个没什么好说的,还是移除自带的Jackson,添加fastjson,不再做过多解释
org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-json com.alibaba fastjson 1.2.74 org.springframework.boot spring-boot-starter-test test
2、User实体(上边代码)
3、UserController(上边代码)
4、WebMvcConfig
#在fastjson中稍微和之前两种不一致
#在FastJsonHttpMessageConverter找到FastJsonConfig看一下
/** *@Create_Authormsfh *@Create_Date2020-11-2516:05:56 *@DescriptionWebMvcConfig配置类 */ @Configuration publicclassWebMvcConfig{ @Bean FastJsonHttpMessageConverterfastJsonHttpMessageConverter(){ FastJsonHttpMessageConverterconverter=newFastJsonHttpMessageConverter(); FastJsonConfigconfig=newFastJsonConfig(); config.setDateFormat("yyyy/MM/dd"); converter.setFastJsonConfig(config); returnconverter; } }
5、测试(无问题)
到此这篇关于SpringBoot整合Gson整合Fastjson的文章就介绍到这了,更多相关SpringBoot整合Gson内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。