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

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

主类

@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批注,则代码将按预期工作,并且我不太明白为什么。任何帮助深表感谢。

最佳答案

当反序列化由@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;
    }
}

10-07 16:22