问题:fastjson默认不会序列化空值属性
解决办法:fastjson 1.2. 提供了相关配置枚举类*
1.导入jar(版本太低将无法支持下面配置类)
<!--添加fastjson依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.53</version>
</dependency>
2.fastjson的SerializerFeature枚举值
QuoteFieldNames———-输出key时是否使用双引号,默认为true
WriteMapNullValue——–是否输出值为null的字段,默认为false
WriteNullNumberAsZero—-数值字段如果为null,输出为0,而非null
WriteNullListAsEmpty—–List字段如果为null,输出为[],而非null
WriteNullStringAsEmpty—字符类型字段如果为null,输出为”“,而非null
WriteNullBooleanAsFalse–Boolean字段如果为null,输出为false,而非null
3.序列化时加入SerializerFeature即可
JSON.toJSONString(Object object, SerializerFeature.WriteMapNullValue)
4.springboot项目可以自行编写配置类
package com.yayaapp.config;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
/**
* 添加fastjson的转换
*/
@Configuration
public class FastjsonConverter {
@Bean
public HttpMessageConverters customConverters() {
// 定义一个转换消息的对象
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
// 添加fastjson的配置信息 比如 :是否要格式化返回的json数据
FastJsonConfig fastJsonConfig = new FastJsonConfig();
// 这里就是核心代码了,WriteMapNullValue把空的值的key也返回
fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteMapNullValue);
List<MediaType> fastMediaTypes = new ArrayList<MediaType>();
// 处理中文乱码问题
fastJsonConfig.setCharset(Charset.forName("UTF-8"));
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
fastConverter.setSupportedMediaTypes(fastMediaTypes);
// 在转换器中添加配置信息
fastConverter.setFastJsonConfig(fastJsonConfig);
StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
stringConverter.setDefaultCharset(Charset.forName("UTF-8"));
stringConverter.setSupportedMediaTypes(fastMediaTypes);
// 将转换器添加到converters中
return new HttpMessageConverters(stringConverter,fastConverter);
}
}