好吧,首先我可以驗證用戶,如果我使用@Valid
並且傳入的是User
實例而不是json字符串。這工作正常e.g:註釋驗證
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String addUser(@Valid @ModelAttribute("user") User user, BindingResult result) {
userRep.save(user);
return "redirect:/";
}
所以,問題是我如何可以自動創建某種API和傳入的JSON字符串,並驗證了註釋,例如,@Email
,@NotEmpty
?最佳做法是什麼?
@RequestMapping(method = RequestMethod.POST, headers = "Accept=application/json")
public ResponseEntity<String> createFromJson(@RequestBody String json) {
User user = User.fromJsonToUser(json);
return new ResponseEntity<String>(user.toJson(),header,HttpStatus.CREATED);
}
User.class
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotEmpty
@Length(max = 30)
private String firstName;
@Email
@NotEmpty
@Length(min = 3 , max = 50)
private String primaryEmail;
}
您可以使用@Va註釋一個帶'@ RequestBody'註釋的參數蓋子「。 –
'@有效'json字符串? ('@ RequestBody''@ Valid' String json),但我想驗證User對象 – Jaxox