Spring的Bindingresult for json Body包含嵌套的不同类型的对象

时间:2018-04-01 12:39:48

标签: java json spring bean-validation hibernate-validator

我有一个场景,其中json请求由不同的自定义对象组成,如:

{
 "person:":{
    "name":"xyx",
    "age":25
  },
  "movieList":[
     {
       "name":"yyy",
       "duration":34,
       "language":"english"
     },
     {
       "name":"zzz",
       "duration":37,
       "language":"english"
     }
   ]

}

,java类看起来像

public class Customer{
 private Person person,
 private List<MovieList> movieList;
}

验证条件:字段不能为空

现在来到spring控制器我希望验证来自请求的每个对象,并且我能够验证整个Customer对象,因为BindingResult应用于整个请求Body.But我的要求是验证Person Object和MovieList对象分开。

public void createCustomer(@RequestBody Customer customer,BindingResult result){
}

而且我的要求是抛出一个特殊对象的异常,导致异常发生,因为我的框架就是这样设计的。

2 个答案:

答案 0 :(得分:1)

您可以使用spring框架中的验证注释。它将验证POJO中的每个字段。请查看以下示例。在MovieList中使用相同的方法。

import javax.validation.constraints.AssertTrue;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.validation.constraints.Email;

public class Person{

@NotNull(message = "Name cannot be null")
private String name;

@AssertTrue
private boolean working;

@Size(min = 10, max = 200, message = "About Me must be between 10 and 200 characters")
private String aboutMe;

@Min(value = 18, message = "Age should not be less than 18")
@Max(value = 150, message = "Age should not be greater than 150")
private int age;

@Email(message = "Email should be valid")
private String email;

// standard setters and getters 
 }

答案 1 :(得分:0)

首先,记下PersonMovieList的验证码(基于自定义验证或注释)。 正如您所说,您想分别验证PersonMovieList对象,您可以编写验证器,然后进行手动验证: -

validator.validate(person, bindingResult);  
if (bindingResult.hasErrors()) {  
    //throw your exception for person object  
}

validator.validate(movieList, bindingResult);  
if (bindingResult.hasErrors()) {  
    //throw your exception for movieList object  
}//Or iterate through each object

要抛出异常,你可以根据字段错误或ObjectError来抛出。

for (Object object : bindingResult.getAllErrors()) {
    if(object instanceof FieldError) {
        FieldError fieldError = (FieldError) object;
        //throw error
    }

    if(object instanceof ObjectError) {
        ObjectError objectError = (ObjectError) object;
        //throw error
    }
}

希望它有所帮助!