Reputation: 187
I'm trying to generate a JSON response using my own Java entity classes together with Jackson annotations. Two key values must be null
in my JSON response but if I set them to null
they disappear from JSON. I'm limited to Jackson version 1.9.13 unfortunately.
I already tried set values to null
, using
@JsonSerialize(include = JsonSerialize.Inclusion.ALWAYS)
My response entity:
public class Response {
@JsonProperty("data")
private Data data;
@JsonProperty("error")
private Error error;
public Data getData() {
return data;
}
public void setData(PgSoftAuthData data) {
this.data = data;
}
public Error getError() {
return error;
}
public void setError(PgSoftError error) {
this.error = error;
}
}
I'm trying to generate response like this:
Data data = new Data();
data.setName("Name");
data.setTime(null); // This key dissappear from JSON
Response responseSuccess = Response();
responseSuccess.setData(data);
responseSuccess.setError(null); // Error object disappear from JSON
I would like to get following response:
{
"data" : {
"name" : "Name",
"time" : null
},
"error" : null
}
Upvotes: 10
Views: 39659
Reputation: 187
Thank you for your answers! As I mentioned I'm limited to Jackson 1.9.13 and I tried multiple combinations with following Jackson annotation but unsuccessfully:
@JsonSerialize(include = JsonSerialize.Inclusion.ALWAYS)
Then I used following:
@XmlElement(nillable = true)
annotation on error and name attributes and it works. Now I get proper JSON response.
Error attribute solution:
@XmlElement(nillable = true)
@JsonProperty("error")
private Error error;
Upvotes: 3
Reputation: 58782
Add JsonInclude to relevant classes Response
and Data
(updated using @ThomasFritsch comment)
@JsonInclude(JsonInclude.Include.ALWAYS)
Value that indicates that property is to be always included, independent of value of the property.
Upvotes: 8