2013-10-25 162 views
0

好吧,首先我可以驗證用戶,如果我使用@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; 

} 
+0

您可以使用@Va註釋一個帶'@ RequestBody'註釋的參數蓋子「。 –

+0

'@有效'json字符串? ('@ RequestBody''@ Valid' String json),但我想驗證User對象 – Jaxox

回答

0

簡單地讓Spring解析字符串給用戶,並且具有相同@Valid註釋標註爲:

@RequestMapping(method = RequestMethod.POST, headers = "Accept=application/json") 
public ResponseEntity<String> createFromJson(@RequestBody @Valid User user) {  
    return new ResponseEntity<String>(user.toJson(), header, HttpStatus.CREATED); 
} 

甚至

@RequestMapping(method = RequestMethod.POST, headers = "Accept=application/json") 
public ResponseEntity<User> createFromJson(@RequestBody @Valid User user) {  
    return new ResponseEntity<User>(user, header, HttpStatus.CREATED); 
} 
+0

但是如何? spring不會僅僅將json字符串解析爲User對象,爲了使它工作,我需要做些什麼? – Jaxox

+0

我不知道我錯過了什麼。我得到了錯誤 - 服務器拒絕了這個請求,因爲請求實體的格式不被請求的資源所請求的方法支持() – Jaxox

+0

您必須在類路徑中包含Jackson JSON映射器。請參閱本文檔中的http://docs.spring.io/spring/docs/3.2.4.RELEASE/spring-framework-reference/htmlsingle/#view-json-mapping和grep「Jackson」。 –