Spring MVC配置阿里巴巴 fastjson

配置阿里巴巴Fastjson

  • 增加依赖包
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.2.38</version>
</dependency>
  • 方式1 mvc配置文件中配置
<!--  启动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>
					</list>
				</property>
				<property name="features">
					<list>
						<value>WriteMapNullValue</value>
						<value>QuoteFieldNames</value>
					</list>
				</property>
			</bean>
		</mvc:message-converters>
	</mvc:annotation-driven>

Fastjson的SerializerFeature序列化属性:
QuoteFieldNames———-输出key时是否使用双引号,默认为true
WriteMapNullValue——–是否输出值为null的字段,默认为false
WriteNullNumberAsZero—-数值字段如果为null,输出为0,而非null
WriteNullListAsEmpty—–List字段如果为null,输出为[],而非null
WriteNullStringAsEmpty—字符类型字段如果为null,输出为”“,而非null
WriteNullBooleanAsFalse–Boolean字段如果为null,输出为false,而非null

fastjson入口类是com.alibaba.fastjson.JSON,主要的API是JSON.toJSONString,和parseObject。

//序列化:转换为json字符串
  String jsonString = JSON.toJSONString(obj);
//反序列化: 将字符串转换为对象
JSON.parseObject("...", target.class);
  • 通过注解配置 FastJSON
    注解直接注入FastJsonHttpMessageConverter,通过@Bean注入HandlerAdapter来注入FastJsonHttpMessageConverter
/**
	 * 加入基于注解方式整合fastjson
	 * 可以参考添加如下配置.
	 */
	
	//整合fastjson库
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    	//1.构建MessageConverter对象
    	FastJsonHttpMessageConverter msConverter = new FastJsonHttpMessageConverter();
    	//2.配置MessageConverter对象
    	//2.1设置fastjson基本配置
    	FastJsonConfig config = new FastJsonConfig();
    	config.setSerializeConfig(SerializeConfig.globalInstance);
    	//禁用循环引用问题
    	config.setSerializerFeatures(
    			SerializerFeature.DisableCircularReferenceDetect);
    	msConverter.setFastJsonConfig(config);
    	
    	//2.2 设置MessageConverter对象对媒体的支持
    	List<MediaType> list = new ArrayList<>();
    	list.add(new MediaType("text", "html", Charset.forName("utf-8")));
    	list.add(new MediaType("application", "json", Charset.forName("utf-8")));
    	msConverter.setSupportedMediaTypes(list);  	
    	//3.将MessageConverter对象添加到converters容器
		converters.add(msConverter);   	
    }

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_16183731/article/details/84845200