解决fastjson不输出空字符串/设置fastjson空值也显示

原文地址:https://blog.csdn.net/moshowgame/article/details/82823430

问题背景
//设置
Map < String , Object > jsonMap = new HashMap< String , Object>();
jsonMap.put("a",111);
jsonMap.put("b","aaa");
jsonMap.put("c",null);
jsonMap.put("d","blog.csdn.net/moshowgame");

//输出
String str = JSONObject.toJSONString(jsonMap);
System.out.println(str);

//输出结果:{"a":111,"b":"aa",d:"blog.csdn.net/moshowgame"}
1
2
3
4
5
6
7
8
9
10
11
12
从输出结果可以看出,只要value为空,key的值就会被过滤掉,这明显不是我们想要的结果,会导致一些坑爹的行为。

解决方案
这时我们就需要用到fastjson的SerializerFeature序列化属性,也就是这个方法:

JSONObject.toJSONString(Object object, SerializerFeature... features)
1
SerializerFeature有用的一些枚举值

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

如果是几句代码,直接就
String jsonStr =
JSONObject.toJSONString(object,SerializerFeature.WriteMapNullValue);

如果是项目,需要配置FastjsonConverter.java了

package com.softdev.system.likeu.config;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.serializer.SerializerFeature;
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.config.FastJsonConfig;
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);
}
}
————————————————
版权声明:本文为CSDN博主「Moshow郑锴」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/moshowgame/java/article/details/82823430

原文地址:https://www.cnblogs.com/eyesfree/p/12768025.html