1,fastjson的优点:
1.1,fastjson可以只依赖于jdk环境,其他的条件可以不用依赖
1.2, fastjson可以进行序列化和反序列换(所谓的序列化就是将对象转换成对应的json字符串,反序列化就是将json字符串进行转换成对应的对象)
1.3,fastjson进行json转换的的速度远远大于jackjson
2,配置开发常用ssm(spring+spring mvc+mybatis) 环境和spring-boot使用fastjson
2,1:在ssm环境下使用fastjson
如果项目是搭建在maven环境下的,则需要再pom.xml中引入fastjson的依赖,依赖配置如下:
<!--fastJson解析json -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.29</version>
</dependency>
然后在spring mvc配置文件中配置
<mvc:annotation-driven >
<mvc:message-converters register-defaults="true">
<!-- 配置Fastjson支持 -->
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>application/json</value>
<value>application/xml;charset=UTF-8</value>
</list>
</property>
<property name="features">
<list>
<!--配置返回json字符串是返回null值 -->
<value>WriteMapNullValue</value>
<value>QuoteFieldNames</value>
<!-- 配置日期格式化 -->
<value>WriteDateUseDateFormat</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
配置完之后就可以使用了,如果想使用fastjson的格式换,可以在对应的属性上使用@@JSONFiled()
例:
@jsonFiled(format="yyyyMMdd HHmmss")
private Date creadate;
那么输出的json字符串creadate的日期格式就是指定格式化的模式
如果搭建的项目不是在mavne环境下的,就需要引入fastjson的jar包,其余配置不变
3 Spring boot环境下使用fastjson
3.1在pom.xml配置文件中引入fastjson的依赖,依赖如下:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.29</version>
</dependency>
3.2在spring boot的启动类中中配置fastjon(至于为什么只在spring boot其中类中配置fastjson信息有用呢?没有找到具体答案,后期慢慢研究下),配置信息如下
/**
* 配置fast json信息
* @return
*/
@Bean
public HttpMessageConverters fastjsonHttpMessageConverters(){
//定义一个convert转换消息的对象
FastJsonHttpMessageConverter converter=new FastJsonHttpMessageConverter();
//添加fastjson的配置信息,比如是否要格式化返回的json信息
FastJsonConfig fastJsonConfig=new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
//解决fastjson 中文乱码
List<MediaType> fastMediaTypes = new ArrayList<MediaType>();
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
//将配置信息添加到convert中
converter.setFastJsonConfig(fastJsonConfig);
//将编码配置加入convert中
converter.setSupportedMediaTypes(fastMediaTypes);
HttpMessageConverter<?> httpMessageConverter=converter;
return new HttpMessageConverters(converter);
}
然后便可以根据业务需求进行数据的序列化和反序列化的操作了