简体   繁体   English

了解Jackson的反序列化(fasterxml)

[英]Understanding of deserialisation of Jackson (fasterxml)

How does Jackson deserialisation work when creating a Java object from JSON?

A common conception is that it first calls the No Argument Constructor and then proceeds to call setters. 一个常见的概念是,它首先调用No Argument构造函数,然后继续调用setter。

But , 但是

  • What happens if there is no No Argument Constructor? 如果没有参数构造函数,会发生什么?
  • Can Jackson be asked to choose some other constructor? 可以要求杰克逊选择其他构造函数吗?
  • Is there any issue with Boilerplate code generators like Lombok? Lombok之类的样板代码生成器是否有问题?

Simply put, Jackson first calls a constructor to instantiate an object and then proceeds to call setters on remaining fields. 简而言之,Jackson首先调用构造函数以实例化对象,然后继续在其余字段上调用setter。

Now, how does it decide which constructor to call and what are the remaining fields? 现在,如何确定要调用哪个构造函数以及剩余的字段是什么?

  • If there are no special annotations defined on a constructor, Jackson will always look for No Argument Constructor . 如果在构造函数上没有定义特殊注释,Jackson将始终寻找No Argument Constructor We will come on special annotations shortly. 我们将很快提供特殊注释。 If the Jackson does not find a No Argument constructor, it will throw an error. 如果Jackson找不到No Argument构造函数,它将抛出错误。
  • Since fasterxml 2.7, Jackson also looks for @ConstructorProperties annotation . 从fastxml 2.7开始, Jackson还寻找@ConstructorProperties注解 In case of multiple constructors having this annotation, it will choose the one with maximum arguments. 如果有多个具有此批注的构造函数,它将选择带有最大参数的批注。 For the rest of the fields, it calls their setter. 对于其余字段,它称为设置器。
  • You can also use @JsonCreator to call a specific constructor . 您还可以使用@JsonCreator调用特定的构造函数 But @ConstructorProperties will still interfere with it. 但是@ConstructorProperties仍然会干扰它。 Even though @JsonCreator can be used on a single constructor, @ConstructorProperties can be used on many. 即使@JsonCreator可以在单个构造函数上使用,@ ConstructorProperties也可以在多个构造函数上使用。
  • Lombok annotates its All Args Constructor with @ConstructorProperties annotation . Lombok使用@ConstructorProperties注释来注释其All Args构造函数 So that might interfere with default Jackson working as well. 因此,这也可能会干扰默认的Jackson工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM