问题重现
- 首先新建一个map向里面put key和value
Map < String , Object > testMap= new HashMap< String , Object>(16);
testMap.put("test1","value1");
testMap.put("test2","value2");
testMap.put("test3",null);
String testStr = JSONObject.toJSONString(testMap);
System.out.println(testStr);
输出结果:{"test2":"value2","test1":"value1"}
细心的同学可能已经发现了 这里少了第三次put的key和value (“test3”,null)
出现原因
这是因为fastjson在进行序列化时只要value为空,key的值就会被过滤掉
解决方式
方式一
- 使用fastjson的SerializerFeature序列化WriteMapNullValue属性:
JSONObject.toJSONString(testMap,SerializerFeature.WriteMapNullValue);
- 扩展:SerializerFeature可能会使用到的枚举值
QuoteFieldNames:输出key时是否使用双引号,默认为true
WriteMapNullValue:是否输出值为null的字段,默认为false
WriteNullNumberAsZero:数值字段如果为null,输出为0,而非null
WriteNullListAsEmpty:List字段如果为null,输出为[],而非null
WriteNullStringAsEmpty:字符类型字段如果为null,输出为”“,而非null
WriteNullBooleanAsFalse:Boolean字段如果为null,输出为false,而非null
方式二:配置fastjson的转换器
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
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 java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
/**
* fastjson的转换
*
* @author ruyi
* @date 2021-12-07 14:16:18
*/
@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(StandardCharsets.UTF_8);
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
fastConverter.setSupportedMediaTypes(fastMediaTypes);
// 在转换器中添加配置信息
fastConverter.setFastJsonConfig(fastJsonConfig);
StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
stringConverter.setDefaultCharset(StandardCharsets.UTF_8);
stringConverter.setSupportedMediaTypes(fastMediaTypes);
// 将转换器添加到converters中
return new HttpMessageConverters(stringConverter, fastConverter);
}
}
如何选择解决方式:
-
如果只是需要当前的一个操作不过滤掉null值\空字符串,那么建议用方式一
-
如果整个项目都需要不过滤掉null值\空字符串显示出来,那么建议用方式二