JacksonJsonSubTypesMap的默认Lombok值

gcuhipw9  于 2022-11-08  发布在  Java
关注(0)|答案(1)|浏览(101)

我想在这个类中添加一个名为negate的布尔字段。

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

但是我在relationEntityTypeFilter.getNegate()上得到了NullPointer,当controller接收到{ "relationType": "Contains", "entityTypes": []}这样的JSON时,也就是说,negate字段应该设置为false,但是这并没有发生
这里是JsonSubTypes
第一个

j9per5c4

j9per5c41#

使用Boolean作为字段类型不会给您带来任何好处, Package 类型对于在Collection中进行存储以及其他需要引用类型的情况非常有用(在Java中不能使用原语作为泛型类型,至少对于)。在所有其他情况下,请使用普通原语boolean,首先,它要干净得多,因为它只有两个可能的值falsetruefalse是默认值)。
如果将negate的类型从 Package 类型更改为基元boolean,则在传入的JSON中缺少该属性且没有任何额外注解时,它将被反序列化为false
请考虑以下简化类:

@NoArgsConstructor
@Getter
@Setter
@ToString
public static class RelationEntityTypeFilter {
    private boolean negate;
}

反序列化示例:

String negateIsMissing = "{ }";
String negateIsFalse = """
    {
        "negate" : "false"
    }
    """;

ObjectMapper mapper = new ObjectMapper();

System.out.println(mapper.readValue(negateIsMissing, RelationEntityTypeFilter.class));
System.out.println(mapper.readValue(negateIsFalse, RelationEntityTypeFilter.class));
  • 输出:*
RelationEntityTypeFilter(negate=false)
RelationEntityTypeFilter(negate=false)

相关问题