如何在Spring中强制请求包含所有属性?

问题描述 投票:0回答:2
@AllArgsConstructor
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = false)
public class RetailerPincodeMapping {

    @Id
    private String id;

    @NotEmpty
    @Indexed
    private Long retailerId;

    @NotEmpty
    @Indexed
    private Integer pincode;

    private boolean active;

    @NotEmpty
    private String deliveryMode;

    @CreatedDate
    private Date createdAt;

    @LastModifiedDate
    private Date lastModifiedAt;

}

目前有一个类是这样定义的。一个理想的请求将是:

{
        "retailerId": 239,
        "pincode": 40061,
        "deliveryMode": "COURIER",
        "active": true
}

假设如果显式地将零售商ID设置为null或任何其他不能被解析为Long的值,我会得到一个错误(期望的行为),但如果我在请求中完全跳过这个属性,它就会将其视为null(不期望的)。

{
        "retailerId" : null //Throws error (desired)
        "pincode": 40061,
        "deliveryMode": "COURIER",
        "active": true
}
{
        "pincode": 40061, // Doesn't throw an error (Undesired)
        "deliveryMode": "COURIER",
        "active": true
}

我怎样才能避免这种情况?我想让请求失败,如果所有需要的属性都不在其中。

json spring spring-boot
2个回答
0
投票

我想你在这里说的是反序列化的问题。你有没有尝试使用 @JsonInclude 注释?你也可以使用你的自定义解串器。@JsonDeserialize. 你是否有 @Valid 注解在控制器层的参数上?


0
投票

正如M. Deinum所回答的,你需要对非空字段进行额外的验证。你应该使用@NotNull。

@NotEmpty
@NotNull
@Indexed
private Long retailerId; 

JFY,比较不同的验证规则。

String name = null;  
@NotNull = false  
@NotEmpty = false  
@NotBlank = false  

String nam = "";  
@NotNull = true  
@NotEmpty = false  
@NotBlank = false  

String name = "  ";  
@NotNull = true  
@NotEmpty = true  
@NotBlank = false  

String name = "string"  
@NotNull = true  
@NotEmpty = true  
@NotBlank = true  
© www.soinside.com 2019 - 2024. All rights reserved.