Jackson 反序列化器 - 将空集合更改为空集合 [英] Jackson deserializer - change null collection to empty one
问题描述
我有一个包含集合作为属性的实体:
I have an entity that contains collection as attribute:
public class Entity {
@JsonProperty(value="homes")
@JsonDeserialize(as=HashSet.class, contentAs=HomeImpl.class)
private Collection<Home> homes = new ArrayList<Home>();
}
如果请求包含 null 作为请求属性:
If request contains null as request property:
{
"homes": null
}
然后家被设置为空.我想要做的是将家设置为空列表.我需要为此编写特殊的反序列化器还是有一个用于集合?我尝试的是这个反序列化器,但它看起来很丑(它不是通用的并且使用实现而不是接口).
then homes is set to null. What I want to do is to set homes to empty list. Do I need to write special deserializer for this or is there one for collections? What I tried is this deserializer but it looks ugly (it's not generic and uses implementation instead of interface).
public class NotNullCollectionDeserializer extends JsonDeserializer<Collection<HomeImpl>> {
@Override
public Collection<HomeImpl> deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
return jsonParser.readValueAs(new TypeReference<Collection<HomeImpl>>(){});
}
@Override
public Collection<HomeImpl> getNullValue() {
return Collections.emptyList();
}
}
这么几个问题:
- 是否有一些 jackson 属性在反序列化期间将 null 更改为空集合?
- 如果第一点没有 - 我是否需要为此编写反序列化器?如果是,我可以写一个通用的吗?
推荐答案
我也找不到 Jackson 属性或对此的注释.所以我必须对第一个问题回答否".但我会推荐一个简单的 setter 而不是特殊的解串器:
I also couldn't find a Jackson property or annotation for this. So I'll have to answer no to the first question. But I would recommend a simple setter instead of the special deserializer :
public class Entity {
@JsonDeserialize(contentAs = HomeImpl.class)
private Collection<Home> homes = new ArrayList<>();
public void setHomes(List<Home> homes) {
if (homes != null)
this.homes = homes;
}
}
这是通用的,因为它只使用 Home
接口而不是 HomeImpl
.您不需要 @JsonProperty
,因为 Jackson 会将 setHomes
和 homes
关联起来.
This is generic as it only uses the Home
interface instead of HomeImpl
. You don't need @JsonProperty
as Jackson will associate setHomes
and homes
.
这篇关于Jackson 反序列化器 - 将空集合更改为空集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!