簡體   English   中英

Spring 啟動 - 驗證請求正文 json 密鑰

[英]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;
}

您可以使用Jackson來解析 JSON 並處理未知屬性。 如果按照此處所述找到未知屬性,它將自動拋出 UnrecognizedPropertyException

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM