Jackson: how to include null value property in JSON serialization

11,467

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;
Share:
11,467
pbjerry10
Author by

pbjerry10

Updated on June 04, 2022

Comments

  • pbjerry10
    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 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
    }
    
  • Thomas Fritsch
    Thomas Fritsch over 5 years
    and add it also to Data class
  • pbjerry10
    pbjerry10 over 5 years
    I can use only @JsonSerialize(include = JsonSerialize.Inclusion.ALWAYS) and it doesn't work.
  • softwarevamp
    softwarevamp over 5 years
    How can i do the same to a HashMap?
  • Radhesh Khanna
    Radhesh Khanna almost 4 years
    Somehow not working in Jackson version 2.11.0 as well