Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson : Conditional select the fields

Tags:

jackson

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

}
like image 611
Rahul Reddy Avatar asked Feb 02 '12 02:02

Rahul Reddy


2 Answers

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

like image 123
StaxMan Avatar answered Sep 24 '22 15:09

StaxMan


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).

like image 38
bluecollarcoder Avatar answered Sep 21 '22 15:09

bluecollarcoder