首页 > 解决方案 > @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反序列化?

标签: javajacksondeserializationlombokbuilder

解决方案


类上的 Jackson 注释也必须存在于构建器类上才能对反序列化产生影响。@JsonNamingLombok 1.18.14 引入了自动复制到构建器类。

但是,io.freefair.lombok5.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”前缀。


推荐阅读