Rahul Reddy
Rahul Reddy

Reputation: 131

Jackson : Conditional select the fields

I have a scenario where i need to use the payload as 

{"authType":"PDS"}
or
{"authType":"xyz","authType2":"abc",}
or
{"authType":"xyz","authType2":"abc","authType3":"123"}
or
any combination except for null values.

referring to the code i have 3 fields but only not null value fields be used. Basically i don't want to include the field which has null value.

Are there any annotations to be used to get it done

public  class AuthJSONRequest {

    private String authType;
    private String authType2;
    private String authType3;

    public String getAuthType() {
        return authType;
    }

    public void setAuthType(String authType) {
        this.authType = authType;
    }

    public String getAuthType2() {
        return authType2;
    }

    public void setAuthType2(String authType2) {
        this.authType2 = authType2;
    }
        public String getAuthType3() {
        return authType3;
    }

    public void setAuthType3(String authType3) {
        this.authType3 = authType3;
    }

}

Upvotes: 7

Views: 7336

Answers (2)

bluecollarcoder
bluecollarcoder

Reputation: 14399

This is exactly what the annotation @JsonInclude in Jackson2 and @JsonSerialize in Jackson are meant for.

If you want a property to show up only when it is not equal to null, add @JsonInclude(Include.NON_NULL) resp. @JsonSerialize(include=Include.NON_NULL).

Upvotes: 5

StaxMan
StaxMan

Reputation: 116492

Try JSON Views? See this or this. Or for more filtering features, see this blog entry (Json Filters for example).

Upvotes: 10

Related Questions