CustardBun
CustardBun

Reputation: 3857

Jackson JSONDeserialize + Builder with different field name?

I'm pretty new to using Jackson and I'm trying to follow my team's patterns for deserializing our JSON. Right now I am running into an issue when a field name doesn't match the JSON property.

Working example:

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

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

If the JSON property is hasProfile, it works fine, but if it's has_profile (which is what our client is writing), it doesn't work and I get an error: Unrecognized field "has_profile" (class com.mypackagehere.something.$ProfilePrimaryData$Builder), not marked as ignorable (one known property: "hasProfile"]). I've tried adding a JsonProperty annotation to hasProfile like this but it still doesn't work:

@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 {
    }
}

Am I misunderstanding how this is supposed to work?

Upvotes: 0

Views: 3427

Answers (1)

Hemant Patel
Hemant Patel

Reputation: 3260

Error clearly says that Unrecognized field "has_profile" (class com.mypackagehere.something.$ProfilePrimaryData$Builder)
i.e has_profile is missing from Builder class, not ProfilePrimaryData class, so you have to annotate Builder class properties.

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

Upvotes: 2

Related Questions