案例
Map< String, Object> fastJsonMap = new HashMap < String, Object> ( ) ;
List nullList = null;
List emptyList = new ArrayList ( ) ;
fastJsonMap. put ( "num" , 1 ) ;
fastJsonMap. put ( "emptyStr" , "" ) ;
fastJsonMap. put ( "nullValue" , null) ;
fastJsonMap. put ( "str" , "baidu.com" ) ;
fastJsonMap. put ( "nullList" , nullList) ;
fastJsonMap. put ( "emptyList" , emptyList) ;
String str = JSONObject. toJSONString ( fastJsonMap) ;
输出结果
{ "str" : "baidu.com" , "emptyList" : [ ] , "emptyStr" : "" , "num" : 1 }
修改
String str = JSONObject. toJSONString ( fastJsonMap,
SerializerFeature. WriteMapNullValue,
SerializerFeature. WriteNullListAsEmpty) ;
输出结果
{ "str" : "baidu.com" , "emptyList" : [ ] , "emptyStr" : "" , "num" : 1 , "nullValue" : null, "nullList" : null}
SerializerFeature属性
枚举值 解释 QuoteFieldNames 输出key时是否使用双引号,默认为true WriteMapNullValue 是否输出值为null的字段,默认为false WriteNullNumberAsZero 数值字段如果为null,输出为0,而非null WriteNullListAsEmpty List字段如果为null,输出为[],而非null WriteNullStringAsEmpty 字符类型字段如果为null,输出为”“,而非null WriteNullBooleanAsFalse Boolean字段如果为null,输出为false,而非null