The influence of Java serialization on field names

influence java serialization field names


There was a problem some time ago , After serialization, the property names in the original class have changed , Original isDel The result of serialization is del, For this reason, I checked the relevant information , Discovery has to do with serialization

In Alibaba Java About this in the development manual , There was one 『 mandatory 』 Regulations :

 

 

So we're going to take a look POJO Different naming of Boolean variables in

class Model1 {
private Boolean isSuccess;
public void setSuccess(Boolean success) {
isSuccess = success;
}
public Boolean getSuccess() {
return isSuccess;
}
}
class Model2 {
private Boolean success;
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
}
class Model3 {
private boolean isSuccess;
public boolean isSuccess() {
return isSuccess;
}
public void setSuccess(boolean success) {
isSuccess = success;
}
}
class Model4 {
private boolean success;
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
}

Of the above code setter/getter It's using Intellij IDEA Automatically generated , Watch the code above carefully , You will find the following rules :

  • Automatic generation of basic types getter and setter Method , Names are isXXX() and setXXX() Formal .
  • Package types are automatically generated getter and setter Method , Names are getXXX() and setXXX() Formal .

We can find out , although Model3 and Model4 The names of member variables in are different , One is success, The other is isSuccess, But they automatically generate getter and setter The names of the methods are isSuccess and setSuccess.

About Java Bean Medium getter/setter The definition of a method is clearly defined , according to JavaBeans(TM) Specification Regulations , If it's a normal parameter propertyName, Define it in the following way setter/getter:

 https://download.oracle.com/otndocs/jcp/7224-javabeans-1.01-fr-spec-oth-JSpec/

public <PropertyType> get<PropertyName>();
public void set<PropertyName>(<PropertyType> a);
public boolean is<PropertyName>();
public void set<PropertyName>(boolean m);

You can see boolean Variable methods of type are defined separately , Use is The way

By comparing this JavaBeans standard , We found that , stay Model4 in , A variable called isSuccess, If it's strictly defined in the code , His getter The method should be called isIsSuccess. But a lot of IDE Will default to be born into isSuccess.

In serialization , This will be affected

@Data
class Model3 implements Serializable {
private static final long serialVersionUID = 1836697963736227954L;
private Integer age;
private String name;
private boolean isSuccess;
private boolean isDel;
public String getUser(){
return "Hello JWZ";
}
}

We define a class , Use lombok, Then look at serialization to test

 // Order one Model3 type 
Model3 model3 = new Model3();
model3.setSuccess(true);
// Use fastjson(1.2.46) serialize model3 Form a string and output 
System.out.println("Serializable Result With fastjson :" + JSON.toJSONString(model3));
// Use Gson(2.8.5) serialize model3 Form a string and output 
Gson gson =new Gson();
System.out.println("Serializable Result With Gson :" +gson.toJson(model3));
// Use jackson(2.9.6) serialize model3 Form a string and output 
ObjectMapper om = new ObjectMapper();
System.out.println("Serializable Result With jackson :" +om.writeValueAsString(model3));

The results are as follows :

You can see three ways to serialize ,

fastjson Output data with values , contain user, belt is Is serialized without is

Gson Output data with values , It doesn't contain user, belt is The fields of are serialized properly

Jackson Output all values and null The data of , contain user, belt is Is serialized without is

So we can draw a conclusion :

fastjson and Jackson It's traversal through reflection getter Method , And then according to JavaBeans He'll take out the rules is To get the property value .

Gson Is to traverse all the properties in the class through direct reflection .

 

Now let's try , For the same object , If you use fastjson serialize , And then use Gson Deserialization :

 public static void main(String[] args) {
Model3 model3 = new Model3();
model3.setSuccess(true);
String fastJSONString=JSON.toJSONString(model3);
System.out.println(fastJSONString);
Gson gson =new Gson();
System.out.println(gson.fromJson(fastJSONString,Model3.class));
}

 

 isSuccess It turned into false

because JSON The framework scans all the getter I found out that there was one isSuccess Method , And then according to JavaBeans The specification of , The variable name is resolved as success, hold model After the object serializes the city string, the content is {"success":true}.

according to {"success":true} This json strand ,Gson After the framework is parsed , Looking for by reflection Model Class success attribute , however Model Class only isSuccess attribute , therefore , After the final deserialization Model Class ,isSuccess The default value will be used false.

therefore , Try to use success To avoid this problem from the source .

extend , Boolean type definitions should use Boolean still boolean

Should boolean type use wrapper type or basic data type ?

 

 

public class Test {
public static void main(String[] args) {
Model3 model3 = new Model3();
System.out.println("model3 : " + model3);
}
}
@Data
class Model3 implements Serializable {
boolean success;
Boolean del;
}

 

The default value for the wrapper type is null, The default value of the basic type is output false, This can cause problems in some cases , It is suggested that POJO and RPC The wrapper type is used in the return value of

So when you define boolean type variables , You should use :

Boolean success;

 

 

Reference resources :

《Java The way for engineers to become gods 》

《 Alibaba Java Development Manual 》

版权声明
本文为[Who left the new bottle to the old moon? This month was the sam]所创,转载请带上原文链接,感谢
https://javamana.com/2021/02/20210223143110719q.html

  1. Add filter and execute filter in excel by Java
  2. Dialogue in spring
  3. 解决Docker MySQL无法被宿主机访问的问题
  4. Oracle OCP 19c 认证1Z0-083考试题库(第1题)
  5. Solve the problem that docker MySQL cannot be accessed by the host
  6. Oracle OCP 19C certification 1z0-083 examination question bank (question 1)
  7. 在 2021 年你需要掌握的 7 种关于 JavaScript 的数组方法
  8. Seven array methods for JavaScript you need to master in 2021
  9. 在 2021 年你需要掌握的 7 种关于 JavaScript 的数组方法
  10. Struts2 + Json _ 配置,异常解决及深入了解Struts2返回JSON数据的原理及具体应用范例
  11. Seven array methods for JavaScript you need to master in 2021
  12. Struts2 + Json _ Configuration, exception resolution and in-depth understanding of Struts2 return JSON data principle and specific application examples
  13. (三)MySQL锁机制 + 事务
  14. (3) MySQL lock mechanism + transaction
  15. 在 2021 年你需要掌握的 7 种关于 JavaScript 的数组方法
  16. Seven array methods for JavaScript you need to master in 2021
  17. 基于Kafka和Elasticsearch构建实时站内搜索功能的实践
  18. Practice of building real time search function in the website based on Kafka and elasticsearch
  19. Golang 实现 Redis(9): 使用GeoHash 搜索附近的人
  20. RxHttp - 轻量级、可扩展、易使用、完美兼容MVVM、MVC架构的网络封装类库
  21. Golang 实现 Redis(9): 使用GeoHash 搜索附近的人
  22. RxHttp - 轻量级、可扩展、易使用、完美兼容MVVM、MVC架构的网络封装类库
  23. Golang realizes redis (9): using geohash to search nearby people
  24. Rxhttp - lightweight, extensible, easy to use, perfectly compatible with MVVM, MVC architecture network encapsulation class library
  25. Golang realizes redis (9): using geohash to search nearby people
  26. Rxhttp - lightweight, extensible, easy to use, perfectly compatible with MVVM, MVC architecture network encapsulation class library
  27. 读懂框架设计的灵魂 — Java 反射机制
  28. 治疗磁盘空间不足焦虑症,释放容器占用空间——Win10+docker篇
  29. 别再用jodatime了!全网最权威Java8日期时间类LocalDate、LocalDateTime详解
  30. Understanding the soul of framework design java reflection mechanism
  31. 配置客户端以安全连接到Apache Kafka集群4:TLS客户端身份验证
  32. Treating anxiety of insufficient disk space and releasing space occupied by containers -- win10 + docker
  33. Don't use jodatime any more! The most authoritative java 8 date and time classes in the whole network: detailed explanation of localdate and localdatetime
  34. Configure clients to connect securely to Apache Kafka Cluster 4: TLS client authentication
  35. Spring break
  36. 高性能MySQL(三):Schema与数据类型优化
  37. High performance mysql (3): schema and data type optimization
  38. redis解决缓存、击穿、雪崩
  39. redis
  40. 骑士卡:基于Kafka搭建消息中心,上亿消息推送轻松完成
  41. Redis solves cache, breakdown and avalanche
  42. redis
  43. Knight card: build a message center based on Kafka, and push hundreds of millions of messages easily
  44. Oracle OCP 19c 认证1Z0-083考试题库(第2题)
  45. redis的三种模式
  46. kubernetes和docker----2.学习Pod资源
  47. 谈一谈如何远程访问MySQL(腾讯云,云主机)
  48. Linux(五):Linux的文档编辑器Vi
  49. Oracle OCP 19C certification 1z0-083 examination question bank (question 2)
  50. 云原生项目实践DevOps(GitOps)+K8S+BPF+SRE,从0到1使用Golang开发生产级麻将游戏服务器—第6篇
  51. kubernetes和docker----2.学习Pod资源
  52. JSP基于Java开发Web应用程序特点有哪些?
  53. Three modes of redis
  54. Kubernetes and docker -- 2. Learning pod resources
  55. Linux (5): the document editor VI of Linux
  56. Cloud native project practice Devops (gitops) + k8s + BPF + SRE, using golang to develop production level mahjong game server from 0 to 1
  57. Kubernetes and docker -- 2. Learning pod resources
  58. What are the characteristics of JSP developing web application based on Java?
  59. Lottie error: java.lang.AssertionError : android.util.JsonReader .peek
  60. Rxhttp - lightweight, extensible, easy to use, perfectly compatible with MVVM, MVC architecture network encapsulation class library