@JsonIgnore with Conditions

Viewed 2338

Is it possible to serialize a JSON response while excluding some elements based on If conditions?

if(a == 1) {
   //show element
} else {
   //don't show element
}

I've tried using @JSONIgnore, but that simply ignores the element regardless of conditions. I'm new to this space. Any ideas?

EDIT: I'm working on enterprise software, so using 3rd party libraries and such won't be a possibility.

2 Answers

You could use custom Jackson serializer.

public class ConditionalValueSerializer extends StdSerializer<Integer> {
    public ConditionalValueSerializer() {
        this(null);
    }

    public ConditionalValueSerializer(Class<Integer> t) {
        super(t);
    }

    @Override
    public void serialize(Integer a, JsonGenerator gen, SerializerProvider provider) throws IOException {
        if(a == 5 ){
            gen.writeString(a.toString());
        } else {
            gen.writeString("");
        }

    }
}

Then use the custom serializer in the object.

public class SomeThing {
    public String name;

    @JsonSerialize(using = ConditionalValueSerializer.class)
    public Integer value;
}

I know your question is about @JsonIgnore, but you may want to try @JsonInclude:

@JsonInclude(value = JsonInclude.Include.CUSTOM, 
             valueFilter = CustomValueFilter.class)
private Integer value;
public class CustomValueFilter {

    @Override
    public boolean equals(Object other) {

        Integer a = (Integer) other;
        return a == 1;
    }
}
Related