java - @JsonNaming 不与 lombok builder 一起使用
问题描述
我正在上课
@JsonNaming(PropertyNamingStrategy.UpperCamelCaseStrategy.class)
public class Test {
String tTObj;
String value;
public String gettTObj() {
return tTObj;
}
public void settTObj(final String tTObj) {
this.tTObj = tTObj;
}
public String getValue() {
return value;
}
public void setValue(final String value) {
this.value = value;
}
public static void main(final String[] args) throws IOException {
final String json = "{\"TTObj\" : \"hi\", \"Value\": \"hello\"}";
final ObjectMapper objectMapper = new ObjectMapper();
final Test test = objectMapper.readValue(json, Test.class);
System.out.println(test);
}
}
以上一个工作正常并且能够反序列化。
但是如果我使用 lombok builder 进行反序列化,它就会失败。
下面是用于反序列化的带有 lombok 构建器的类
@JsonDeserialize(builder = Test.Builder.class)
@Value
@Builder(setterPrefix = "with", builderClassName = "Builder", toBuilder = true)
@JsonNaming(PropertyNamingStrategy.UpperCamelCaseStrategy.class)
public class Test {
String tTObj;
String value;
public static void main(final String[] args) throws IOException {
final String json = "{\"TTObj\" : \"hi\", \"Value\": \"hello\"}";
final ObjectMapper objectMapper = new ObjectMapper();
final Test test = objectMapper.readValue(json, Test.class);
System.out.println(test);
}
}
得到以下错误
Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "TTObj" (class com.demo.Test$Builder), not marked as ignorable (2 known properties: "value", "ttobj"])
at [Source: (String)"{"TTObj" : "hi", "Value": "hello"}"; line: 1, column: 13] (through reference chain: com.demo.Test$Builder["TTObj"])
如何 "{"TTObj" : "hi", "Value": "hello"}"
使用带有lombok builder的@JsonNaming反序列化?
解决方案
类上的 Jackson 注释也必须存在于构建器类上才能对反序列化产生影响。@JsonNaming
Lombok 1.18.14 引入了自动复制到构建器类。
但是,io.freefair.lombok
5.1.0 版中的 Gradle 插件默认使用 Lombok 1.18.12 版。所以这是一个太旧的版本(Lombok 仅使用偶数作为次要/补丁级别编号)。
您可以使用更新版本的 Gradle 插件,或者通过以下方式手动配置它以使用更新的 Lombok 版本build.gradle
:
lombok {
version = "1.18.20"
}
PS:使用 Lombok >= 1.18.14,您可以考虑使用@Jacksonized
而不是手动配置您的构建器:
@Value
@Jacksonized
@Builder(builderClassName = "Builder", toBuilder = true)
@JsonNaming(PropertyNamingStrategy.UpperCamelCaseStrategy.class)
public class Test {
...
}
在这种情况下,您不需要@JsonDeserialize
注释和“with”前缀。
推荐阅读
- python - 如何显示通过 Python (JayDeBeApi) 从 Dynamics 365 Online 中提取的行?
- pandas - 如何使用多索引分配给 Pandas.Series 中的新行?
- go - 通过 jenkins 部署 go 应用程序
- javascript - JQuery 自动关闭在运行时创建的 li
- android - React Native 的 Android 构建失败
- apache-spark - 使用 Google CloudDataproc 时是否还需要微调 spark 配置参数?
- reactjs - Webpack 构建抛出“.sourceMap 是 .sourceMaps 的别名,不能同时使用”
- java - JavaFX - 如何在场景顶部添加“图像”?
- c# - 在 ASP.net 中设置和 API(URL 问题?)
- javascript - Angularjs 指令,做模板的不同方式来避免 {{}} 解析问题