将空集合更改为空集合

将空集合更改为空集合

本文介绍了杰克逊反序列化器 - 将空集合更改为空集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含集合作为属性的实体:

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
}

然后将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();
  }
}

问题很少:


  1. 是否有一些jackson属性在反序列化期间将null更改为空集合?

  2. 如果第一点没有 - 我需要吗?为此写反序列化器?如果是的话,我可以写一般的吗?


推荐答案

我也找不到杰克逊属性或注释。所以我不得不回答第一个问题。但我会推荐一个简单的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;
    }
}

这是通用的,因为它只使用主页界面而不是 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.

这篇关于杰克逊反序列化器 - 将空集合更改为空集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 18:51