fastjson 保留null值
我们需要用到fastjson的SerializerFeature序列化属性
也就是这个方法:JSONObject.toJSONString(Object object, SerializerFeature... features)
Fastjson的SerializerFeature序列化属性
QuoteFieldNames———-输出key时是否使用双引号,默认为true
WriteMapNullValue——–是否输出值为null的字段,默认为false
WriteNullNumberAsZero—-数值字段如果为null,输出为0,而非null
WriteNullListAsEmpty—–List字段如果为null,输出为[],而非null
WriteNullStringAsEmpty—字符类型字段如果为null,输出为”“,而非null
WriteNullBooleanAsFalse–Boolean字段如果为null,输出为false,而非null
1. JSONObject.toJSONString过滤掉null
System.out.println(JSONObject.toJSONString(da)); //解决方式: System.out.println(JSONObject.toJSONString(da, SerializerFeature.WriteMapNullValue));
2.字符串转换JSONObject.parseObject,
jsonObject.getString取值会过滤掉null
String responseString = "{\"result\":{\"code\":\"200\",\"data\":{\"code01\":null,\"code02\":null,\"idCardNo\":\"367202199909149038\",\"bz\":null,\"u_by5\":null,\"code03\":null,\"u_by2\":null,\"uuId\":\"7183f93f30a540fbb7544d0e2296a987\",\"u_by1\":null,\"processTime\":null,\"u_by4\":null,\"u_by3\":null},\"message\":\"请求成功\"},\"code\":0}"; JSONObject respObject = JSONObject.parseObject(responseString); String result = respObject.getString("result") //分析:JSONObject.parseObject 这里其实不过滤null
JSONObject respObject = JSONObject.parseObject(responseString); JSONObject resultJson = respObject.getJSONObject("result"); String resultJsonString = JSONObject.toJSONString(resultJson, SerializerFeature.WriteMapNullValue); log.info("resultJson: {}",resultJsonString);
3.附加场景
描述:当前端数据通过fastjson序列化传到后端,调用数据库端口时属性为null,放到数据库进行判断处理?
这时候可以使用FastJSON提供的@JSONField中有一个属性serialzeFeatures,这个可以进行判空处理,当为null值时,该属性不进行序列化。
@JSONField(serialzeFeatures=SerializerFeature.WriteMapNullValue,name="user_name") private String userName;
参考: https://blog.csdn.net/qq_34103387/article/details/125790200