工具类如下:
public class StatusUtils {
public static Object userInfoObj = null;
public final static String MESSAGE = "message";
public final static String RESULT = "result";
public final static String SUCCESS = "success";
public static ValueFilter FASTJSONFILTER = new ValueFilter() {
@Override
public Object process(Object obj, String s, Object v) {
if(v==null) {
return "";
}
return v;
}
};
}
阿里其实是给出了好多种过滤方案,但是经实践之后,对于springboot框架并不是非常兼容,就比如能够输出null并将其转换为空值的过滤方法就不能真正把null转成空值,所以我为此借鉴了其他大佬给出的解决方案。就是重新复写一个过滤方案。
@Slf4j
@RestController
@RequestMapping("/DemoController")
public class DemoController {
@Autowired
private DemoService demoService;
......
@RequestMapping("/demo")
@ResponseBody
public void demo(HttpServletRequest request, HttpServletResponse response,
Model model,@RequestBody JSONObject data)
throws IllegalStateException, IOException {
String jsonObjectSrc = null;
JSONObject jsonObject = new JSONObject(3);
jsonObject.put("success",status);
jsonObject.put("message",map.get(StatusUtils.MESSAGE).toString());
jsonObject.put("data",map.get(StatusUtils.RESULT));
jsonObjectSrc = JSON.toJSONString(jsonObject, StatusUtils.FASTJSONFILTER);
try {
response.getWriter().print(jsonObjectSrc);
} catch (IOException e) {
e.printStackTrace();
}
}
}
上述代码中JSON.toJSONString的引用包是import com.alibaba.fastjson.JSON
自带的解决方案是这样的:
QuoteFieldNames———-输出key时是否使用双引号,默认为true
WriteMapNullValue——–是否输出值为null的字段,默认为false
WriteNullNumberAsZero—-数值字段如果为null,输出为0,而非null
WriteNullListAsEmpty—–List字段如果为null,输出为[],而非null
WriteNullStringAsEmpty—字符类型字段如果为null,输出为”“,而非null
WriteNullBooleanAsFalse–Boolean字段如果为null,输出为false,而非null
// 使用方式
String str = JSONObject.toJSONString(jsonMap,SerializerFeature.WriteMapNullValue);
因为使用自带方法不管用,所以就用了jsonObjectSrc = JSON.toJSONString(jsonObject, StatusUtils.FASTJSONFILTER);这个办法。这个办法经测试是可以的。
附加:
springboot+mybatis在SQL的值是null时也是不获取的,解决办法是在application.properties里面添加如下代码:
# sql为null时也要获取该属性值
mybatis.configuration.call-setters-on-nulls=true