Jackson: how to include null value property in JSON serialization
Solution 1
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.
Solution 2
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;
pbjerry10
Updated on June 04, 2022Comments
-
pbjerry10 about 2 years
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 tonull
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 }
-
Thomas Fritsch over 5 yearsand add it also to
Data
class -
pbjerry10 over 5 yearsI can use only @JsonSerialize(include = JsonSerialize.Inclusion.ALWAYS) and it doesn't work.
-
softwarevamp over 5 yearsHow can i do the same to a HashMap?
-
Radhesh Khanna almost 4 yearsSomehow not working in Jackson version 2.11.0 as well