与lombok Builder一起使用Jackson,@ JsonIdentityInfo和@JsonDeserialize时出现UnrecognizedPropertyException

时间:2018-12-10 15:49:18

标签: java lombok jackson2

我正在尝试序列化和反序列化非常大的对象图。为了减小生成的JSON的大小,我以为我会使用Jackson的@JsonIdentityInfo批注,该批注似乎在此特定用例下效果很好。

但是,当我添加时,它会炸毁。硬。示例代码如下:

Main.class

@Data
@Builder
@JsonDeserialize(builder = Main.MainBuilder.class)
@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class)
public class Main {

    private final String name;
    @Singular
    private final Map<String, Main> mains;

    public static void main(String[] args) throws IOException {
        var test = Main.builder()
                .name("Root")
                .main("One", Main.builder()
                        .name("One")
                        .build())
                .main("Two", Main.builder()
                        .name("Two")
                        .build())
                .main("Three", Main.builder()
                        .name("Three")
                        .build())
                .build();

        var om = new ObjectMapper();
        var result = om.writeValueAsString(test);
        System.out.println(result);
        var back = om.readValue(result, Main.class);
    }

    @JsonPOJOBuilder(withPrefix = "")
    public static class MainBuilder {
    }
}

build.gradle

plugins {
    id 'java'
    id 'application'
}

repositories {
    jcenter()
    mavenCentral()
}

sourceCompatibility = 11
targetCompatibility = 11

mainClassName = 'dk.acto.Main'


dependencies {
    compileOnly 'org.projectlombok:lombok:1.18.0'
    implementation 'com.fasterxml.jackson.core:jackson-databind:2.9.7'
    annotationProcessor "org.projectlombok:lombok:1.18.0"
}

如果您注释掉@JsonIdentityInfo批注,则代码将按预期工作,并且我不太明白为什么。非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

当反序列化由@JsonIdentityInfo添加的@id字段时,它将失败。您需要处理@id字段。

@JsonIgnoreProperties添加到您的构建器将阻止其失败。

@JsonPOJOBuilder(withPrefix = "")
@JsonIgnoreProperties(ignoreUnknown=true)
public static class MainBuilder {
}

将@id添加到您的构建器中

@JsonPOJOBuilder(withPrefix = "")
public static class MainBuilder {
    private int id;
    @JsonProperty(value="@id")
    public MainBuilder id() {
        this.id = id;
        return this;
    }
}