【问题标题】:Spring boot - Validating request body json keySpring Boot - 验证请求正文 json 键
【发布时间】:2020-03-14 10:49:18
【问题描述】:

我正在验证 Spring Boot 中的请求正文。 当 post 控制器使用下面的 JSON 在数据库中创建记录时。它工作正常。

{
  "test1": "string",
  "test2": "string",
  "test3": "string",  <--this has @Null in the entity
  "test4": "string"
}

但是,当实体中的一个键是@NULL 时,它仍然能够在数据库中创建一条记录。我想知道是否有可以验证密钥并返回错误的东西。

{
  "test1": "string",
  "test2": "string",
  "test5": "string", <- wrong key by mistake
  "test4": "string"
}

实体类

@Entity
@Table(name = "test")
@Data
@NoArgsConstructor
public class Test implements Serializable {

@Id
@Column(name = "test1")
private String test1;

@Column(name = "test2")
@NotNull
private String test2;

@Column(name = "test3")
private String test3;

@Column(name = "test4")
private String test4;
}

【问题讨论】:

  • @Null 还是@NotNull。是否可以给出一段最少的可重现代码,以便我们更好地获取上下文并提供帮助
  • 它是@Null,所以如果该字段拼写错误,它将显示“test3” = null,因为它可以是空值。
  • 添加了test1为id,test2不为空,test3和test4允许空值的示例实体类。
  • @NotNull(message = "") 你可以留言
  • 假设 test3 和 test4 允许空值。当请求 JSON 没有“test3”时,它将替换为空值。如果用户在“test3”->“test5”字段上犯了错误,它不会告诉错误。

标签: java json spring-boot


【解决方案1】:

您可以使用Jackson 来解析 JSON 并处理未知属性。如果发现未知属性,它将自动抛出 UnrecognizedPropertyException,如 here 所述。

【讨论】:

    【解决方案2】:
    If u want to Validate request body in JSON u can use @Valid
    
          @PostMapping("/books")
        Book newBook(@Valid @RequestBody Test test) {
            return repository.save(Test);
        }
    
    @Column(name = "test3")
    @NotNull(message = "Please provide a test3")
    private String test3;
    
    if u want on key order
     JsonPropertyOrder({ "test1", "test2", "test3", "test4" })
    public class Test implements Serializable {
    }
    

    【讨论】:

      猜你喜欢
      • 2020-10-18
      • 2018-08-08
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-11
      相关资源
      最近更新 更多