如何使用杰克逊排除空列表项 [英] How to exclude null list items with Jackson
问题描述
我正在调用一个API,该API返回一个值数组,这些值将转换为 List< SomeEnum>
.响应中的某些值不再在枚举中定义.这些值在列表中显示为 null
值.
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.
我想知道是否有一种方法可以告诉杰克逊(假装)在反序列化时排除 null
列表项.
I am wondering if there is a way to tell Jackson (or feign) to exclude null
list items when deserializing.
我查看了 @JsonInclude
,但这适用于 null
属性,而不适用于 null
收集项.
I've looked at @JsonInclude
but this applies to null
properties and not null
collection items.
编辑
这些值显示为null的原因是因为正在使用选项 DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL
.
The reason the values show up as null is because the option DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL
is being used.
推荐答案
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 +
'}';
}
}
上面的代码显示:
{"days":[null,"Monday","Tuesday",null,"Friday",null]}
Created{days=[Monday, Tuesday, Friday]}
编辑
如果您有未知的枚举值,则上述解决方案将不起作用.在这种情况下,您应该使用 DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL
或 DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE
功能.一种解决方法是手动从 null
-s中过滤集合:
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...
这篇关于如何使用杰克逊排除空列表项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!