创建类的首选方法是什么

  • Immutable
  • Can be serialized/deserialized with Jackson
  • Human-readable and with low level of boilerplate

最好是,我希望这样的工作:

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

然后所有字段都是private final.然而,这甚至没有编译(我不知道为什么).使用

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

将编译,但只会产生

InvalidDefinitionException: No serializer found for class

推荐答案

add ConstructorProperties:

  • Create a lombok.config file in an appropriate location with the line: lombok.anyConstructor.addConstructorProperties = true
  • 将Lombok@Value注释添加到您的类中,使其不可变

然后,Jackson的序列化和反序列化工作如期进行.

这种方法:

Edit: 2020-08-16

  • 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.

Edit: 2021-08-19

  • 注意:添加或更改lombok.config文件时,除非进行重建(先清理后生成),否则不会拾取更改.我已经被这件事困扰了好几次.
  • @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.

Json相关问答推荐

如何在Haskell中解析JSON,其中字段的名称可以是多个值之一,但应该转换为单个Haskell类型?

在Jolt中将具有嵌套元素的对象数组转换为单独的对象列表

当由.sh脚本执行时,AWS查询字符串不会提取任何数据

使用不同行数的数据创建嵌套Jolt

如何在 jq 中按 IP 地址排序?

从 Inno Setup 中的 JSON 文件的每个对象中读取特定字符串

try 使用 JQ 转换 JSON 中过于复杂的对象数组

Powershell - 如何从 JSON 中删除/过滤元素但保留其余部分?

从 PowerShell 编辑 Windows 终端配置文件设置 JSON

如何使用 ConfigurationBuilder 解析现有的 json 字符串(不是文件)

以 JSON 格式访问(新型、公共)Google 工作表

避免 KeyError 的默认字典键

JBuilder中未定义的局部变量或方法json

如何一次加载无限滚动中的所有条目以解析python中的HTML

如何使用 C# 将 JSON 文本转换为对象

Json.Net:用于自定义命名的 JsonSerializer-Attribute

使用 jq,将对象数组转换为具有命名键的对象

是否可以将数据写入本地 json 文件,除了Angular 之外什么都没有?

[__NSCFNumber 长度]:发送到实例 UITableView 的无法识别的 Select 器

如何将单引号转义成双引号转成单引号