当前位置:网站首页>Do not add the is prefix to the variables of the boolean type in the POJO class of the Alibaba specification
Do not add the is prefix to the variables of the boolean type in the POJO class of the Alibaba specification
2022-08-11 07:13:00 【geekmice】
说明
【强制】POJO 类中的任何布尔类型的变量,都不要加 is 前缀,否则部分框架解析会引起序列
化错误.
说明:在本文 MySQL 规约中的建表约定第一条,表达是与否的变量采用 is_xxx 的命名方式,所以,需要
in settings from is_xxx 到 xxx 的映射关系.
反例:定义为基本数据类型 boolean isDeleted 的属性,它的方法也是 isDeleted(),框架在反向解析的时
候,“误以为”对应的属性名称是 deleted,导致属性获取不到,进而抛出异常.
问题复现
准备工作
1、需要的依赖
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
2、对应java文件
public class App {
public static void main(String[] args) {
TempOne temp = new TempOne();
temp.setLive(true);
TempTwo tempTwo = new TempTwo();
tempTwo.setLive(true);
System.out.println("temptwo isLive:" + new Gson().fromJson(JSON.toJSONString(tempTwo),TempTwo.class));
System.out.println("temp live:"+ new Gson().fromJson(JSON.toJSONString(temp), TempOne.class));
}
}
3、执行后效果
temptwo isLive:TempTwo{isLive=false}
tempone live:Temp{live=true}
4、结果分析
TempTwoclass has beenisLive属性设置为true,Why return is indeedfalse,原因是因为JSON框架通过扫描所有的getter后发现有一个isLive方法,然后根据JavaBeans的规范,解析出变量名为live,把model对象序列化城字符串后内容为{“live”: true}.
然后根据{“live”: true}这个json串,Gson框架在通过解析后,通过反射寻找People类中的live属性,但是TempTwo类中只有isLive属性,找不到对应的属性,所以,最终反序列化后的TempTwo类的对象中,isLive则会使用默认值false
As a result, the boolean type data in the foreground cannot be sent to the background,Since the front desk will pass it over, it will be namedisXThe variable resolves to X,但是我们pojoThe Boolean type property in the class isisX,导致找不到X,So passing the value fails;
Finally explained:pojoDo not add boolean-like variablesis前缀
注意点
所有的POJO类属性必须使用包装数据类型.
RPC方法的返回值和参数必须使用包装数据类型.
所有的局部变量使用基本数据类型.
boolean类型的默认值为false;而Boolean类型的默认值是null
边栏推荐
猜你喜欢
随机推荐
iptables 基础配置
抖音分享口令url API工具
window10吐槽
unable to extend table xxx by 1024 in tablespace xxxx
HCIP MGRE\OSPF综合实验
【LeetCode】851.喧闹与富有(思路+题解)
maxwell 概念
训练分类器
kill 命令
HCIP OSPF/MGRE Comprehensive Experiment
【LeetCode】1036. 逃离大迷宫(思路+题解)压缩矩阵+BFS
ansible batch install zabbix-agent
八股文之jvm
每日sql-找到每个学校gpa最低的同学(开窗)
arcgis填坑_3
每日sql-统计各个专业人数(包括专业人数为0的)
torch.cat()用法
淘宝API接口参考
arcgis填坑_4
HCIP BGP建邻、联邦、汇总实验