I was looking for the same thing.
According to the Jackson docs, we can set a @JsonIgnore
annotation on a property, getter or setter and that would hide the complete property, unless we give the setter a @JsonProperty
annotation that would make sure this property is visible when setting it. Unfortunately, that doesn't work the other way around. I wanted to show the property in my response, but not include it in my request.
Use case is an auto generated id for example. I don't want the user to set, or even see that, but he may read it.
You can achieve this by hiding the attribute itself indeed and then add a @JsonAnyGetter
method. In this method you can massage the data to any form you want. It's also useful to represent complex attribute classes of which you only want to show a single name or identifier or other formatting. There are better ways of doing the latter, but if the use case is not too complex, this suffices.
So as example (My apologies if this is too elaborate):
User:
public class User {
private String uid;
private String customerId;
private String taxSsnId;
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getCustomerId() {
return extCustomerId;
}
public void setCustomerId(String extCustomerId) {
this.extCustomerId = extCustomerId;
}
public String getTaxSsnId() {
return taxSsnId;
}
public void setTaxSsnId(String taxSsnId) {
this.taxSsnId = taxSsnId;
}
@JsonIgnore
public void getId(){
if (getUid() != null){
return getUid();
}
if (getCustomerId() != null ){
return getCustomerId();
}
return null;
}
}
Setting:
public class Setting {
@JsonIgnore
private int id;
private String key;
private String value;
@JsonIgnore
private User lastUpdatedBy;
@JsonIgnore
private Date lastUpdatedAt;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public User getLastUpdatedBy() {
return lastUpdatedBy;
}
public void setLastUpdatedBy(User lastUpdatedBy) {
this.lastUpdatedBy = lastUpdatedBy;
}
public Date getLastUpdatedAt() {
return lastUpdatedAt;
}
public void setLastUpdatedAt(Date lastUpdatedAt) {
this.lastUpdatedAt = lastUpdatedAt;
}
@JsonAnyGetter
private Map<String, String> other() {
Map<String, String> map = new LinkedHashMap<String, String>();
map.put( "id", this.getId());
map.put( "lastUpdatedBy", this.getLastUpdatedBy().getId());
SimpleDateFormat format = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
map.put( "lastUpdatedAt", format.format(this.getLastUpdatedAt()) );
return map;
}
}
Yields this Request
schema (de-serialization view):
{
"key": "string",
"value": "string"
}
and this Response
schema (serialized view):
{
"key": "string",
"value": "string",
"id": "12345",
"lastUpdatedBy": "String",
"lastUpdatedAt": "String"
}