spring-mvc项目中使用Fastjson作为json消息的转换器

spring-mvc项目中使用Fastjson作为json消息的转换器

Fastjson

阿里出品,速度快,体积小。虽然出过几次安全漏洞,但我还是喜欢用它。

<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.62</version>
</dependency>

spring-mvc中整合

<mvc:annotation-driven>
	<mvc:message-converters register-defaults="true">
		<!-- 处理响应为text/plain时的body编码 -->
		<bean class="org.springframework.http.converter.StringHttpMessageConverter">
			<constructor-arg index="0" value="UTF-8" />
		</bean>
		<!-- 使用fastjson序列化json数据 -->
		<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
			<!-- 支持处理的contentType -->
			<property name="supportedMediaTypes">
				<list>
					<value>application/json</value>
				</list>
			</property>
			<!-- 配置类 -->
			<property name="fastJsonConfig">
				<bean class="com.alibaba.fastjson.support.config.FastJsonConfig">
					<property name="charset" value="UTF-8" />
					<!-- 更多配置项参见枚举: SerializerFeature -->
					<property name="serializerFeatures">
						<array>
							<!-- 消除循环依赖 -->
							<value>DisableCircularReferenceDetect</value>
						</array>
					</property>
					<!-- 默认的日期对象格式化 -->
					<property name="dateFormat" value="yyyy-MM-dd HH:mm:ss" />
				</bean>
			</property>
		</bean>
	</mvc:message-converters>
</mvc:annotation-driven>

spring-boot 使用

spring-mvc并没有太大的区别,以编码的形式创建FastJsonHttpMessageConverter FastJsonConfig 。交给IOC管理即可。

@Bean
public HttpMessageConverters fastJsonHttpMessageConverter() {

	FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();

	FastJsonConfig fastJsonConfig = new FastJsonConfig();
	fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
	fastJsonConfig.setCharset(StandardCharsets.UTF_8);
	fastJsonConfig.setSerializerFeatures(SerializerFeature.DisableCircularReferenceDetect);

	fastJsonHttpMessageConverter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON));
	fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);

	return new HttpMessageConverters(fastJsonHttpMessageConverter);
}

Fastjson的文档

这里只是简单介绍了怎么去整合,关于Fastjson的使用,有详细的中文文档

配合食用