【问题标题】:Jackson JSONDeserialize + Builder with different field name?Jackson JSONDeserialize + Builder具有不同的字段名称?
【发布时间】:2018-11-21 06:18:17
【问题描述】:

我对使用 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 {
    }
}

我是否误解了这应该如何工作?

【问题讨论】:

  • 这可能会对您有所帮助 - stackoverflow.com/questions/16019834/…@JsonIgnoreProperties(value = { "has_profile" }) 类级别注释或更通用的 @JsonIgnoreProperties(ignoreUnknown = true)
  • @SASIKUMARS - 我认为我们不在同一页面上 - 我希望读取 has_profile 字段并将其放入 POJO 的 hasProfile 字段中。 JsonIgnoreProperties 不会把值扔掉吗?
  • 您可以发布示例 JSON 吗?

标签: jackson json-deserialization


【解决方案1】:

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

@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);
        }
    }
}

【讨论】:

    猜你喜欢
    • 2021-01-08
    • 2022-01-03
    • 2016-08-25
    • 2017-03-03
    • 2022-01-09
    • 2017-05-18
    • 2018-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多