How to exclude the empty list from JSON during the Serialization using the Jackson Serializer?

120 views Asked by At

How to avoid writing the empty list using the Jackson Custom serializer? Currently, it's adding the empty list: "list" : [ ] but I want it to completely skip it, either with some annotations or using the custom sealizer. I have created the demo with Collections.emptyList(), I am aware that if I remove then it will skip the empty list but this is just for demo purposes and I want to skip using some other approach:

MyClass:

@Data
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@AllArgsConstructor
public class MyClass {
    private String type;

    private String name;

    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    @JsonSerialize(using = CustomSearilizer.class)
    private List<Object> list;
}

CustomSearilizer:

public class CustomSearilizer extends JsonSerializer<List<Object>> {
    @Override
    public void serialize(final List<Object> context, final JsonGenerator jsonGenerator, final SerializerProvider serializers) throws IOException {

        jsonGenerator.writeStartArray();

        context.stream().forEach(item -> {
            if (item instanceof Map) {
                Map<String, String> entries = (Map<String, String>) item;
                entries.entrySet().stream().forEach(entry -> {
                    try {
                        jsonGenerator.writeStartObject();
                        jsonGenerator.writeStringField(entry.getKey(), entry.getValue());
                        jsonGenerator.writeEndObject();
                    } catch (IOException ex) {
                        throw new RuntimeException(ex);
                    }

                });
            }
        });

        jsonGenerator.writeEndArray();
    }
}

Main:

public class Main {
    public static void main(String[] args) throws JsonProcessingException {
        final ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);

        final MyClass myClass = new MyClass("My Name", "My Type", Collections.emptyList());

        System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(myClass));
    }
}

This is providing me with following JSON:

{
  "type" : "My Name",
  "name" : "My Type",
  "list" : [ ]
}

I would like to create it following JSON:

{
  "type" : "My Name",
  "name" : "My Type"
}

This is just a demo so I have added collections.emptyList to re-create the issue but is there any way I can skip adding these emptyList in JSON when using the customsealizer?

1

There are 1 answers

4
Michael Gantman On

I just ran a test and just adding the annotation @JsonInclude(JsonInclude.Include.NON_EMPTY) to the serialized class did the trick. No other action was needed. No custom serializer and no modification for ObjectMapper configuration. Here is the article that eaplains the example: Jackson JSON - @JsonInclude NON_EMPTY Example