一、什么是fastjson
fastjson是阿里巴巴的開源JSON解析庫,它可以解析JSON格式的字符串,支持將Java Bean序列化為JSON字符串,也可以從JSON字符串反序列化到JavaBean。
二、fastjson的優點
2.1 速度快
fastjson相對其他JSON庫的特點是快,從2011年fastjson發布1.1.x版本之后,其性能從未被其他Java實現的JSON庫超越。
2.2 使用廣泛
fastjson在阿里巴巴大規模使用,在數萬台服務器上部署,fastjson在業界被廣泛接受。在2012年被開源中國評選為最受歡迎的國產開源軟件之一。
2.3 測試完備
fastjson有非常多的testcase,在1.2.11版本中,testcase超過3321個。每次發布都會進行回歸測試,保證質量穩定。
2.4 使用簡單
fastjson的API十分簡潔。
String text = JSON.toJSONString(obj); //序列化
VO vo = JSON.parseObject("{...}", VO.class); //反序列化
- 1
- 2
2.5 功能完備
支持泛型,支持流處理超大文本,支持枚舉,支持序列化和反序列化擴展。
三、引入fastjson依賴庫
maven
<dependencies> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.46</version> </dependency> </dependencies>
gradle
compile("com.alibaba:fastjson:1.2.47")
四、配置方式
方式一:在啟動類中配置
@SpringBootApplication @EnableDiscoveryClient @EnableScheduling public class MemberApplication extends WebMvcConfigurerAdapter { /** * 配置FastJson為方式一 * @return*/ @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { super.configureMessageConverters(converters); /* * 1、需要先定義一個convert轉換消息的對象 2、添加fastJson的配置信息,比如:是否要格式化返回json數據 3、在convert中添加配置信息 * 4、將convert添加到converters當中 * */ // 1、需要先定義一個·convert轉換消息的對象; FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); // 2、添加fastjson的配置信息,比如 是否要格式化返回json數據 FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); // 3、在convert中添加配置信息. fastConverter.setFastJsonConfig(fastJsonConfig); // 4、將convert添加到converters當中. converters.add(fastConverter); } public static void main(String[] args) { SpringApplication.run(MemberApplication.class, args); } }
方式二:通過@Bean方式注入
/** * fastJson替換JackJson */ @Configuration public class HttpConverterConfig { @Bean public HttpMessageConverters fastJsonHttpMessageConverters() { // 1.定義一個converters轉換消息的對象 FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); // 2.添加fastjson的配置信息,比如: 是否需要格式化返回的json數據 FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); // 3.在converter中添加配置信息 fastConverter.setFastJsonConfig(fastJsonConfig); //處理中文亂碼問題 List<MediaType> oFastMediaTypeList = new ArrayList<>(); oFastMediaTypeList.add(MediaType.APPLICATION_JSON_UTF8); fastConverter.setSupportedMediaTypes(oFastMediaTypeList); // 4.將converter賦值給HttpMessageConverter HttpMessageConverter<?> converter = fastConverter; // 5.返回HttpMessageConverters對象 return new HttpMessageConverters(converter); } }
一個實體類(驗證 1.birthday被格式化 2.age字段不返回)
public class Person { private String name; @JSONField(serialize = false) private int age; @JSONField(format = "yyyy-MM-dd HH") private Date birthday; // set和get方法 }