Natasha
Natasha

Reputation: 367

How to tell Jackson to ignore a field given that there is no condition on the field being null?

[Not a repeat].

I need the exact opposite of JsonIgnore. In my use case there is just one field that I need to add in serialization and all others are to be ignored. I've explored @JsonSerialize, @JsonInclude and @JsonProperty but none work as required by me.

Is there a way to achieve this or I'll need to mark the fields to be ignored with @JsonIgnore?

Upvotes: 1

Views: 1314

Answers (2)

hzpz
hzpz

Reputation: 7966

By default, Jackson will auto-detect all getters in your object and serialize their values. Jackson distinguished between "normal" getters (starting with "get") and "is-getters" (starting with "is", for boolean values). You can disable auto-detection for both entirely by configuring the ObjectMapper like this:

ObjectMapper mapper = new ObjectMapper();
mapper.disable(MapperFeature.AUTO_DETECT_GETTERS);
mapper.disable(MapperFeature.AUTO_DETECT_IS_GETTERS); 

Alternatively, you can disable the auto-detection on a per class basis using @JsonAutoDetect. Annotate the fields or getters you actually do want to serialize with @JsonProperty.

@JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE, 
                isGetterVisibility = JsonAutoDetect.Visibility.NONE)
public class MyObject {

    private String foo;

    @JsonProperty("bar")
    private String bar;

    private boolean fubar;

    public MyObject(String foo, String bar, boolean fubar) {
        this.foo = foo;
        this.bar = bar;
        this.fubar = fubar;
    }

    public String getFoo() {
        return foo;
    }

    public String getBar() {
        return bar;
    }

    public boolean isFubar() {
        return fubar;
    }

}

Serializing MyObject like this:

mapper.writeValueAsString(new MyObject("foo", "bar", true));

will result in the following JSON

{"bar":"bar"}

Upvotes: 3

Akshay
Akshay

Reputation: 21

you can try this @JsonIgnoreProperties("propertyName") on the top of variable..

Upvotes: 0

Related Questions