具有不同字段名称的 Jackson JSONDeserialize + Builder?

Jackson JSONDeserialize + Builder with different field name?

我刚开始使用 Jackson,我正在尝试遵循我的团队的模式来反序列化我们的 JSON。现在,我 运行 遇到字段名称与 JSON 属性 不匹配的问题。

工作示例:

@JsonDeserialize(builder = ProfilePrimaryData.Builder.class)
@Value
@ParametersAreNonnullByDefault
@Builder(builderClassName = "Builder")
private static class ProfilePrimaryData {
    private final Boolean hasProfile;

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

如果 JSON 属性 是 hasProfile,它工作正常,但如果它是 has_profile(这是我们的客户正在写的),它就不起作用,我明白了一个错误:Unrecognized field "has_profile" (class com.mypackagehere.something.$ProfilePrimaryData$Builder), not marked as ignorable (one known property: "hasProfile"])。我试过像这样向 hasProfile 添加 JsonProperty 注释,但它仍然不起作用:

@JsonDeserialize(builder = ProfilePrimaryData.Builder.class)
@Value
@ParametersAreNonnullByDefault
@Builder(builderClassName = "Builder")
private static class ProfilePrimaryData {
    @JsonProperty("has_profile")
    private final Boolean hasProfile;

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

我是不是误解了它的工作原理?

错误清楚地说 Unrecognized field "has_profile" (class com.mypackagehere.something.$ProfilePrimaryData$Builder)
Builder class 中缺少 has_profile,而不是 ProfilePrimaryData class,因此您必须注释 Builder class 属性。

@JsonDeserialize(builder = ProfilePrimaryData.Builder.class)
public class ProfilePrimaryData {

    /*
     * This annotation only needed, if you want to
     * serialize this field as has_profile,
     * 
     * <pre>
     * with annotation
     * {"has_profile":true}
     * 
     * without annotation
     * {"hasProfile":true}
     * <pre>
     *  
     */
    //@JsonProperty("has_profile")
    private final Boolean hasProfile;

    private ProfilePrimaryData(Boolean hasProfile) {
        this.hasProfile = hasProfile;
    }

    public Boolean getHasProfile() {
        return hasProfile;
    }

    @JsonPOJOBuilder(withPrefix = "")
    public static class Builder {

        // this annotation is required
        @JsonProperty("has_profile")
        private Boolean hasProfile;

        public Builder hasProfile(Boolean hasProfile) {
            this.hasProfile = hasProfile;
            return this;
        }

        public ProfilePrimaryData build() {
            return new ProfilePrimaryData(hasProfile);
        }
    }
}