1

[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?

Natasha
  • 367
  • 1
  • 5
  • 15
  • Do you want "@Expose" only Gson equivalent ? maybe duplicate of [this question](http://stackoverflow.com/questions/22668374/jackson-serialize-only-marked-fields) – boly38 Jul 21 '15 at 12:43

2 Answers2

3

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"}
hzpz
  • 7,536
  • 1
  • 38
  • 44
0

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

Akshay
  • 21
  • 5