Jackson deserializer - change null collection to empty one

前端 未结 3 684
生来不讨喜
生来不讨喜 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:03

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

    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.

    0 讨论(0)
  • 2020-12-18 19:13

    What worked for me was simply to remove the setter and make the attribute final. jackson 2 will then use the getter to modify the list.

    public class Entity {
    
      @JsonProperty(value="homes")
      @JsonDeserialize(as=HashSet.class, contentAs=HomeImpl.class)
      private final Collection<Home> homes = new ArrayList<Home>();
    
      public List<Home> getHomes() {
         return homes;
      }
    }
    

    The responsible feature is USE_GETTERS_AS_SETTERS which is turned on by default: https://github.com/FasterXML/jackson-databind/wiki/Mapper-Features

    0 讨论(0)
  • 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<String> 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.

    0 讨论(0)
提交回复
热议问题