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