如何用杰克逊排除空列表项

时间:2019-07-18 14:15:22

标签: java json jackson deserialization feign

我正在调用API,该返回的值将转换为List<SomeEnum>的数组。响应中的某些值不再在枚举中定义。这些值在列表中显示为null值。

我想知道反序列化时是否有一种方法告诉Jackson(或伪装)排除null列表项。

我看过@JsonInclude,但这适用于null属性,而不适用于null收集项目。

2 个答案:

答案 0 :(得分:0)

将注释@JsonInclude(Include.NON_NULL)添加到要映射的类。这样可以解决问题

答案 1 :(得分:0)

您可以将JsonSetter注释与Nulls.SKIP一起使用。参见以下示例:

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 +
                '}';
    }
}

上面的代码显示:

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