Jackson deserializer - change null collection to empty one

前端 未结 3 690
生来不讨喜
生来不讨喜 2020-12-18 18:30

I have an entity that contains collection as attribute:

public class Entity {

    @JsonProperty(value=\"homes\")
    @JsonDeserialize(as=HashSet.class, cont         


        
3条回答
  •  误落风尘
    2020-12-18 19:22

    As of Jackson 2.9, it looks like null-handling for specific properties can be configured with @JsonSetter, for example:

    @JsonSetter(nulls = Nulls.AS_EMPTY)
    public void setStrings(List strings) {
        this.strings = strings;
    }
    

    Similar configuration can also be applied globally for collections:

    ObjectMapper mapper = objectMapperBuilder()
        .changeDefaultNullHandling(n -> n.withContentNulls(Nulls.AS_EMPTY))
        .build();
    

    Or by type:

    ObjectMapper mapper = objectMapperBuilder()
        .withConfigOverride(List.class,
            o -> o.setNullHandling(JsonSetter.Value.forContentNulls(Nulls.AS_EMPTY)))
        .build();
    

    I haven't been able to try the feature out, so this is based on the feature discussion and examination of unit tests. YMMV.

提交回复
热议问题