fastjson解析null值问题: 解决 null的属性不显示问题
null对应的key被过滤掉;这明显不是我们想要的结果,这时我们就需要用到fastjson的SerializerFeature序列化属性:
也就是这个方法:
JSONObject.toJSONString(Object object, SerializerFeature... features)
SerializerFeature有用的一些枚举值
QuoteFieldNames———-输出key时是否使用双引号,默认为true
WriteMapNullValue——–是否输出值为null的字段,默认为false
WriteNullNumberAsZero—-数值字段如果为null,输出为0,而非null
WriteNullListAsEmpty—–List字段如果为null,输出为[],而非null
WriteNullStringAsEmpty—字符类型字段如果为null,输出为”“,而非null
WriteNullBooleanAsFalse–Boolean字段如果为null,输出为false,而非null
现在加上
Map < String , Object > jsonMap = new HashMap< String , Object>();
jsonMap.put("a",1);
jsonMap.put("b","");
jsonMap.put("c",null);
jsonMap.put("d","wuzhuti.cn");
String str = JSONObject.toJSONString(jsonMap,SerializerFeature.WriteMapNullValue);
System.out.println(str);
//输出结果:{"a":1,"b":"","c":null,"d":"wuzhuti.cn"}
一个代码实例:
private static final TypeReference<Map<String, Object>> MAP_TYPE_REFERENCE = new TypeReference<Map<String, Object>>() {
};
/**
* @param tenantId
* @param sql
* @param timeout
* @return
* @throws SQLException
*/
@Override
public List<Map<String, Object>> queryWithJsonFormat(Long tenantId, String sql, long timeout) throws SQLException {
// 获取驱动信息
Map<Long, ConnectInfo> connectInfoMap = getDriverInfo().getConnectInfoMap();
String clusterName = connectInfoMap.get(tenantId).getClusterName();
String response = HttpClientUtils.postTextRequest(baseURL(clusterName), buildSQLWithTimeoutAndFormatJson(sql, timeout));
if (response == null || response.isEmpty()) {
return Collections.emptyList();
}
JSONArray dataArray = (JSONArray) JSON.parseObject(response).get("data");
return dataArray.stream()
.map(it ->
JSON.parseObject(JSON.toJSONString(it, SerializerFeature.WriteMapNullValue), MAP_TYPE_REFERENCE)
)
.collect(Collectors.toList());
}
其中, response 返回值的数据结构:
{
"meta": [
{
"name": "uid_basic_profile_edu_degree",
"type": "Nullable(String)"
},
{
"name": "count_uid_basic_profile_edu_degree",
"type": "UInt64"
}
],
"data": [
{
"uid_basic_profile_edu_degree": "college",
"count_uid_basic_profile_edu_degree": 533389
},
{
"uid_basic_profile_edu_degree": null,
"count_uid_basic_profile_edu_degree": 0
},
{
"uid_basic_profile_edu_degree": "undergraduate",
"count_uid_basic_profile_edu_degree": 2518436
},
{
"uid_basic_profile_edu_degree": "master",
"count_uid_basic_profile_edu_degree": 271653
},
{
"uid_basic_profile_edu_degree": "high",
"count_uid_basic_profile_edu_degree": 5585609
}
],
"rows": 5,
"statistics": {
"elapsed": 0.703029803,
"rows_read": 1287687385,
"bytes_read": 76340471397
}
}