Jackson JsonSubTypes映射下Lombok默认值失效引发空指针问题
解决RelationEntityTypeFilter中negate字段默认值不生效的空指针问题
问题原因
- 你给
RelationEntityTypeFilter加了Lombok的@AllArgsConstructor注解,它会生成包含所有字段的全参构造方法,但没有生成无参构造方法。Jackson反序列化JSON时,若类没有无参构造,会调用全参构造创建对象——而JSON里没有negate字段,构造方法中该参数会传入null,直接覆盖了你在字段上设置的= false默认值。 negate字段用的是包装类Boolean,反序列化后值为null,调用getNegate()时就会触发空指针异常。
解决方案
方案1:添加无参构造方法
在RelationEntityTypeFilter类上添加@NoArgsConstructor注解,让Lombok生成无参构造。Jackson会先创建空对象,再为JSON中存在的字段赋值,未赋值的字段会保留你设置的默认值false。
修改后的代码:
@Data @NoArgsConstructor @AllArgsConstructor @ApiModel public class RelationEntityTypeFilter { @ApiModelProperty(position = 1, value = "Type of the relation between root entity and other entity (e.g. 'Contains' or 'Manages').", example = "Contains") private String relationType; @ApiModelProperty(position = 2, value = "Array of entity types to filter the related entities (e.g. 'DEVICE', 'ASSET').") private List<EntityType> entityTypes; @ApiModelProperty(position = 3, value = "Negate relation type between root entity and other entity.") private Boolean negate = false; }
方案2:改用基本类型boolean
如果业务逻辑允许,把Boolean改成boolean。基本类型的默认值就是false,即使Jackson没有为该字段赋值,也不会出现null,从根源避免空指针。
修改后的字段定义:
@ApiModelProperty(position = 3, value = "Negate relation type between root entity and other entity.") private boolean negate; // 基本类型默认值为false,可省略= false
方案3:用Jackson注解指定默认值
给negate字段添加@JsonProperty注解,明确指定默认值,确保反序列化时字段缺失时自动填充。注意部分Jackson版本可能需要额外配置才能识别defaultValue,因此优先推荐前两个方案。
@ApiModelProperty(position = 3, value = "Negate relation type between root entity and other entity.") @JsonProperty(defaultValue = "false") private Boolean negate = false;
内容的提问来源于stack exchange,提问作者devaskim
相关产品推荐
相关产品推荐

