在fastjson中,缺省是不输出空值的。无论Map中的null和对象属性中的null,序列化的时候都会被忽略不输出,这样会减少产生文本的大小。但如果需要输出空值怎么做呢?
使用SerializerFeature.WriteMapNullValue:
Model obj = ...;
JSON.toJSONString(obj, SerializerFeature.WriteMapNullValue);
空值特别处理:
SerializerFeature | 描述 |
---|---|
WriteNullListAsEmpty | 将Collection类型字段的字段空值输出为[] |
WriteNullStringAsEmpty | 将字符串类型字段的空值输出为空字符串 “” |
WriteNullNumberAsZero | 将数值类型字段的空值输出为0 |
WriteNullBooleanAsFalse | 将Boolean类型字段的空值输出为false |
来看一下示例代码:
package json.fastjson.empty;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
public class TestNull {
public static void main(String[] args) {
// WriteNullListAsEmpty 将Collection类型字段的字段空值输出为[]
// WriteNullStringAsEmpty 将字符串类型字段的空值输出为空字符串 ""
// WriteNullNumberAsZero 将数值类型字段的空值输出为0
// WriteNullBooleanAsFalse 将Boolean类型字段的空值输出为false
Model obj = new Model();
System.out.println("------------------加上参数------------------------------");
String text = JSON.toJSONString(obj,
SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.WriteNullStringAsEmpty,
SerializerFeature.WriteNullNumberAsZero,
SerializerFeature.WriteNullBooleanAsFalse,
SerializerFeature.WriteMapNullValue,
SerializerFeature.PrettyFormat);
System.out.println(text + " \n");
System.out.println("------------------不加参数------------------------------");
text = JSON.toJSONString(obj,
SerializerFeature.PrettyFormat);
System.out.println(text);
}
}
class Model {
public int iFull = 9;
public int iEmpty;
public Integer integerFull = 9;
public Integer integerEmpty;
public boolean bFull = true;
public boolean bEmpty;
public Boolean BFull = true;
public Boolean BEmpty;
public List<String> listFull = Arrays.asList("挖", "坑", "埋", "你");
public List<String> listEmpty;
public Map<String, String> mapFull = new HashMap<String, String>() {{put("a", "b");}};
public Map<String, String> mapEmpty;
}
输出结果:
------------------加上参数------------------------------
{
"BEmpty":false,
"BFull":true,
"bEmpty":false,
"bFull":true,
"iEmpty":0,
"iFull":9,
"integerEmpty":0,
"integerFull":9,
"listEmpty":[],
"listFull":[
"挖",
"坑",
"埋",
"你"
],
"mapEmpty":null,
"mapFull":{
"a":"b"
}
}
------------------不加参数------------------------------
{
"BFull":true,
"bEmpty":false,
"bFull":true,
"iEmpty":0,
"iFull":9,
"integerFull":9,
"listFull":[
"挖",
"坑",
"埋",
"你"
],
"mapFull":{
"a":"b"
}
}