【问题标题】:How to force request to contain all the attributes in Spring?如何强制请求包含 Spring 中的所有属性?
【发布时间】:2020-04-28 12:34:27
【问题描述】:
@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
}

假设如果将retailerId 显式设置为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
}

我怎样才能避免这种情况? 如果请求中不存在所有必需的属性,我希望请求失败。

【问题讨论】:

  • 你试过spring验证器了吗?
  • @NotEmpty 允许null 添加一个额外的@NotNull
  • @M.Deinum 那没有解决问题
  • 什么不起作用?它应该,您是否使用了正确的 @NotNull 注释并且您的类路径上是否有一个有效的验证实现,如 hibernate-validator(没有它,注释不会做任何事情!)。

标签: json spring spring-boot


【解决方案1】:

我想你在这里谈论的是反序列化。您是否尝试使用@JsonInclude 注释?您还可以使用您的自定义反序列化器: @JsonDeserialize。你在控制器层的参数上有@Valid注解吗?

【讨论】:

    【解决方案2】:

    正如 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  
    

    【讨论】:

    • @GVSandeep,我认为您的验证配置中遗漏了一些东西。提供您的控制器实现
    猜你喜欢
    • 2018-11-29
    • 1970-01-01
    • 2014-07-01
    • 2011-02-15
    • 1970-01-01
    • 2011-08-01
    • 2021-09-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多