项目场景:
SpringBoot返回结果为null或空值不显示处理方法。
测试场景:
测试过的场景一:最开始是使用JdbcTemplate 查询数据返回,以为是JdbcTemplate 模板的问题,换成了Mybatis。
测试过的场景二:认为是Mybatis 配置 callSettersOnNulls = true 这个配置,就能成功返回。但是尝试了没有效果。
测试过的场景三:将List 转成 json 字符串,最后返回字符串能成功返回NULL值,但是这不符合要求。
测试过的场景四:对数据库的字段 作为空判断(IFNULL ()、NVL() )、取别名,测试过不行。
测试过的场景五: 也尝试了将返回的List集合转成JSONArray,然后通过对应的实体对象转成List 集合,虽然这种成功将数据库查出的NULL 的数据成功返回。但是会将key 键 自动转成小驼峰返回。不符合将数据库字段不变返回的效果。
public void test(){
// dataList
JSONArray jsonArray = parseJSONArrayForListMap(dataList);
String s = jsonArray.toString();
List<BussCustomerInfoColBo> BussCustomerInfoColBos = fromListJson(s, BussCustomerInfoColBo.class);
}
private static <T> List<T> fromListJson(String str,Class<T> clazz){
return JSONArray.parseArray(str, clazz);
}
//判断当前字符串如果为空或者Null则返回字符串 空 ""
private static Object isNullReturnEmpty(Object obj){
if(null == obj || "".equals(obj) ){
return "";//如果获取时间失败,则返回-
}
return obj;
}
/*
* 将List<map>转换为JSONArray,将null替换为""
*/
private static JSONArray parseJSONArrayForListMap(List<Map> listMap) {
JSONArray array = new JSONArray();
for(Map mmp : listMap) {
JSONObject mmpJson = new JSONObject();
Iterator iter = mmp.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
Object key = entry.getKey();
Object val = isNullReturnEmpty(entry.getValue());
mmpJson.put(key+"", val);
}
array.add(mmpJson);
}
return array;
}
测试过的场景六: 测试了这篇文章的转载了 。https://www.cnblogs.com/sunshinekevin/p/12110910.html 。
方法一:自定义消息转换器 (注意注释掉方法二的配置)。成功返回,符合要求。
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter{
/**
* 利用fastjson替换掉jackson
* @param converters
*/
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
super.configureMessageConverters(converters);
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
}
}