与 Jackson 的不可变 Lombok 注释类 [英] Immutable Lombok annotated class with Jackson

查看:81
本文介绍了与 Jackson 的不可变 Lombok 注释类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建类的首选方法是什么

What is the preferred way to create class that is

  • 不可变
  • 可以使用 Jackson 进行序列化/反序列化
  • 人类可读且样板代码较少

最好,我会喜欢这样的工作:

Preferably, I would have liked something like this to work:

@Data(onConstructor = @__(@JsonCreator))

然后让所有字段成为private final.但是,这甚至无法编译(我不确定为什么).使用

and then have all fields to be private final. However, this does not even compile (and I'm not sure why). Using

@AllArgsConstructor(onConstructor = @__(@JsonCreator))

将编译但只产生

InvalidDefinitionException: No serializer found for class

推荐答案

添加ConstructorProperties:

  • 创建一个 lombok.config 文件 在适当的位置:lombok.anyConstructor.addConstructorProperties = true
  • 在类中添加 lombok @Value 注释以使其不可变
  • Create a lombok.config file in an appropriate location with the line: lombok.anyConstructor.addConstructorProperties = true
  • Add lombok @Value annotation to your class to make it immutable

然后杰克逊的序列化和反序列化按预期工作.

Then serialization and deserialization by Jackson works as expected.

这个方法:

  • meets the criteria
  • has less boilerplace than the previous top answer
  • works on v1.16.20 (January 9th, 2018) and later

2020-08-16

  • 注意:将 @Builder@Value 一起使用会导致此解决方案失败.(感谢下面@guilherme-blanco 的评论.)但是,如果您还添加了例如@AllArgsConstructor 它仍然按预期工作.
  • Note: Using @Builder with @Value causes this solution to fail. (Thanks to comment from @guilherme-blanco below.) However, if you also add e.g. @AllArgsConstructor it does still work as expected.

2021-08-19

  • 注意:当您添加或更改 lombok.config 文件时,除非您进行重建(先清理后构建),否则更改不会生效.我已经被这个问题吸引了好几次了.
  • @Jacksonized 注释解决方案 是实现特定类所需结果的另一种方法注释.但是,我个人更喜欢不需要记住对用于反序列化的每个类进行注释.使用 lombok.config 消除了这种开销.
  • Note: When you add or change a lombok.config file the change is not picked up unless you do a rebuild (clean then build). I have been caught out by this a few times.
  • @Jacksonized annotation solution is another method to achieve the desired outcome for the specific classes annotated. However, I personally prefer not to need to remember to annotate every class used for deserialization. Using lombok.config removes this overhead.

这篇关于与 Jackson 的不可变 Lombok 注释类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆