5

I have an issue with JAXB / Jackson marshalling. I have such an annotation

@XmlAttribute(name = "private")
protected Boolean mPrivate;

and I expect that this attribute be absent if the mPrivate variable is null.

This works fine if the output is XML. But if I switch to JSON, using Jackson, the output is

xxxxxxx, "private":null, xxxxxxxx

Anybody has an idea why this happens and how to fix it? Thanks in advance.

bdoughan
  • 147,609
  • 23
  • 300
  • 400
ticofab
  • 7,551
  • 13
  • 49
  • 90
  • See this question: http://stackoverflow.com/questions/11757487/how-to-tell-jackson-to-ignore-a-field-during-serialization-if-its-value-is-null – Michał Ziober Jul 03 '13 at 12:18

1 Answers1

5

Jackson is compatible with the JAXB annotations. Hence JAXB doesn't support default values for XmlAttributes as the default behavior is to leave them out if value is null when serializing to XML.

There are a few options to achieve this for JSON.

  1. You can annotate your POJO with @JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)

  2. You can set the default behavior of the ObjectMapper to exclude null-values from serialisation. You do so by calling:

    setSerializationInclusion(Inclusion.NON_NULL);

    ...on the ObjectMapper instance.

Pepster
  • 1,996
  • 1
  • 24
  • 41
  • I discovered that @JsonSerialize can be added at the class level or the field/method level. If applied at the class level, you can still override at the field/method level. – Blaine Jun 02 '14 at 18:58