Richard Collette
Richard Collette

Reputation: 5703

How to exclude null list items with Jackson

I am calling an API that returns an array of values that are converted to a List<SomeEnum>. Some of the values in the response are no longer defined in the enum. These values appear in the list as null values.

I am wondering if there is a way to tell Jackson (or feign) to exclude null list items when deserializing.

I've looked at @JsonInclude but this applies to null properties and not null collection items.

EDIT

The reason the values show up as null is because the option DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL is being used.

Upvotes: 3

Views: 5564

Answers (2)

Michał Ziober
Michał Ziober

Reputation: 38645

You can use JsonSetter annotation together with Nulls.SKIP. See below example:

import com.fasterxml.jackson.annotation.JsonSetter;
import com.fasterxml.jackson.annotation.Nulls;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Arrays;
import java.util.List;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();

        Work work = new Work();
        work.setDays(Arrays.asList(null, Day.Monday, Day.Tuesday, null, Day.Friday, null));

        String json = mapper.writeValueAsString(work);
        System.out.println(json);
        System.out.println(mapper.readValue(json, Work.class));
    }
}

enum Day {Monday, Tuesday, Wednesday, Thursday, Friday}

class Work {

    private List<Day> days;

    public List<Day> getDays() {
        return days;
    }

    @JsonSetter(contentNulls = Nulls.SKIP)
    public void setDays(List<Day> days) {
        this.days = days;
    }

    @Override
    public String toString() {
        return "Created{" +
                "days=" + days +
                '}';
    }
}

Above code prints:

{"days":[null,"Monday","Tuesday",null,"Friday",null]}
Created{days=[Monday, Tuesday, Friday]}

EDIT
Above solution will not work, if you have unknown enum values. In that case you should use DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL or DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE feature. One workaround would be filtering collection from null-s manually:

public void setDays(List<Day> days) {
    this.days = days.stream().filter(Objects::nonNull).collect(Collectors.toList());
}

Of course, we could implement custom deserialiser for collection and skip it there but...

Upvotes: 4

morrisng
morrisng

Reputation: 125

Add the annotation @JsonInclude(Include.NON_NULL) to the class you wish to map. That will solve the issue

Upvotes: -2

Related Questions