对应阿里巴巴开发手册第一章的命名风格的第八条。
【强制】POJO 类中的任何布尔类型的变量,都不要加 is 前缀,否则部分框架解析会引起序列化错误。
对于这样一条【强制】级别的规定,虽然规范中做了简单的说明,但依然显得很不起眼,以至于很多人依然踩到了这个坑。
当你使用快捷键进行生成getset方法时他会把“is”给吃掉,问题就出在private boolean isAtAll;这个字段上,有没有发现阿里的这个参数违背了开篇提到的开发规范?使用fastjson序列化之后,该属性实际转化为了:“atAll”: true。
具体是什么原因呢,百度之后找到了一篇文章: POJO类中布尔类型为啥不让用isXxx命名 中有提到
为什么序列化之后把is吃了呢?带着这个问题我追踪了一下fastjson的源码,发现在序列化的时候,其使用的是属性的getter方法名,而isAtAll字段自动生成的getter、setter为:
public boolean isAtAll() {
return isAtAll;
}
public void setAtAll(boolean atAll) {
isAtAll = atAll;
}
对应的fastjson中对方法名的处理在com.alibaba.fastjson.util.TypeUtils.computeGetters中,源码摘录如下:
if(methodName.startsWith("is")){
if(methodName.length() < 3){
continue;
}
if(method.getReturnType() != Boolean.TYPE
&& method.getReturnType() != Boolean.class){
continue;
}
String propertyName;
Field field = null;
if(Character.isUpperCase(c2)){
if(compatibleWithJavaBean){
propertyName = decapitalize(methodName.substring(2));
} else{
propertyName = Character.toLowerCase(methodName.charAt(2)) + methodName.substring(3);
}
propertyName = getPropertyNameByCompatibleFieldName(fieldCacheMap, methodName, propertyName, 2);
}
也就是说,对于is开头的方法,fastjson先把第3个字符截取出来,如果该字符是大写,就转换为小写,并且拼装剩余的方法名组成属性名。
例如:isAtAll方法拼装出来的属性名就是atAll,最终结果就是把我们的is给吃了
所以解决方法就是不要用isxxx命名就最简单粗暴