Bilesh Ganguly Bilesh Ganguly - 4 months ago 14
JSON Question

Jackson: Ignore empty fields except those that are mandatory with respect to the project

Following is a POJO class (one of the classes at a certain level of nesting), an object of which, I'm serializing into a JSON using Jackson.

@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Attribute {

private String label;
private String name; // Mandatory
private String description; // Mandatory
private String type; // Mandatory
private Boolean hidden;
private Boolean important;
...


Using
@JsonInclude(JsonInclude.Include.NON_EMPTY)
to only include fields that have values that are not
null
or empty. The issue is that the fields
name
,
description
and
type
are mandatory, that is, they must be present in the generated JSON even if they are
null
or empty. When these fields are provided, I have no problem. But when they are not provided,

instead of this -

"attributes" : [
{
"type" : "Text",
"hidden" : false,
"important" : false,
...


I want this -

"attributes" : [
{
"name" : "",
"description" : "",
"type" : "Text",
"hidden" : false,
"important" : false,
...


Fields
label
,
name
, and
description
are empty in the above case. Also, the class which "has" attributes has it in the form -

List<Attribute> attributes;


That is why, the above JSON is like that.

Any help would be really appreciated.

Answer

I think the suggestion from @chrylis is what you are looking for. The idea to annotate specific fields with @JsonInclude (default value is JsonInclude.Include.ALWAYS) in field level to override the class level @JsonInclude(JsonInclude.Include.NON_EMPTY). Following is an example:

@JsonInclude(JsonInclude.Include.NON_EMPTY)
public static class Attribute {

    private String label;
    @JsonInclude
    private String name;        // Mandatory
    @JsonInclude
    private String description; // Mandatory
    @JsonInclude
    private String type;        // Mandatory
Comments