![](/img/trans.png)
[英]Handling a RequestBody when there are variable key-value in the request json body in spring boot
[英]Spring boot - Validating request body json key
我正在驗證 Spring 啟動中的請求正文。 當發布 controller 使用下面的 JSON 在 DB 中創建記錄時。 它工作正常。
{
"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"
}
實體 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.