[英]Spring boot - Validating request body json key
I am working on validating the request body in Spring boot.我正在验证 Spring 启动中的请求正文。 When the post controller using the below JSON to create record in the DB.
当发布 controller 使用下面的 JSON 在 DB 中创建记录时。 It works fine.
它工作正常。
{
"test1": "string",
"test2": "string",
"test3": "string", <--this has @Null in the entity
"test4": "string"
}
However, when one of the key is @NULL in the entity, it will still able to create a record in the DB.但是,当实体中的一个键是@NULL 时,它仍然能够在数据库中创建一条记录。 I am wondering if there is something that can validate the key and return error.
我想知道是否有东西可以验证密钥并返回错误。
{
"test1": "string",
"test2": "string",
"test5": "string", <- wrong key by mistake
"test4": "string"
}
Entity class实体 class
@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;
}
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 {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.