Reputation: 45
I want to do the run time exclusion in Jackson.
In the below example which has three variables
public class Field {
//------------------------- private variables ----------------------------
private A header;
private B values;
private C argvalues;
//------------------------- constructors ----------------------------------
public Field(A header, B values) {
this.header = header;
this.values = values;
}
public Field(A header, C values) {
this.header = header;
this.argvalues = values;
}
public Field() {
}
//--------------------- getter-setter -------------------------------------
public A getHeader() {
return header;
}
public void setHeader(A header) {
this.header = header;
}
public B getValues() {
return values;
}
public void setValues(B values) {
this.values = values;
}
public C getArgvalues() {
return argvalues;
}
public void setArgvalues(C argvalues) {
this.argvalues = argvalues;
}
}
Suppose if any of the variables are not set at runtime , how do i exclude them from the json. Please help .
<--@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@---->
when we are using @ JsonProperty in the below example
public String getType() {
return type;
}
@ JsonProperty("Json")
public void setType(String type) {
this.type = type;
}
public List<TwoDArrayItem> getItems() {
return items;
}
@ JsonProperty("Json")
public void setItems(List<TwoDArrayItem> items) {
this.items = items;
}
At any point of time i will be setting only one setter method but the JsonProperty name should be same for both . when i am compiling this i am getting error. How to set the same name for both .?
Upvotes: 1
Views: 2512
Reputation: 80633
To always exclude null values for the given object, you can annotate it with:
@JsonSerialize(include=Inclusion.NON_NULL) // Jackson 1.9 or lower
@JsonInclude(Include.NON_NULL) // Jackson 2 or higher
public class Field {
// ...
}
As opposed to excluding null values for the entire object, you can exclude them for specific fields:
public class Field {
private A header;
private B values;
@JsonSerialize(include=Inclusion.NON_NULL) // Jackson 1.9 or lower
@JsonInclude(Include.NON_NULL) // Jackson 2 or higher
private C argvalues;
// ...
}
To dynamically exclude null values for a given session, create an object mapper and configure it too exclude nulls.
final ObjectMapper mapper = new ObjectMapper()
.setSerializationInclusion(Include.NON_NULL);
Upvotes: 1