英文:
Json request validation for mandatory field - springboot rest-api
问题
在下面的JSON请求中,您可以看到工资在3个级别上都是可用的:学生级别、实习生级别和属性级别。
employee{
id: "123";
name: "ABC";
salary: 100;
college: "abcd..";
Trainees: {
id: "101";
name: "XYZ";
salary: 50;
}
properties: {
default.salary= 20
default.college=null
}
}
由于在我的应用程序中工资是必需的,因此工资应该至少在一个级别上可用。
如果在所有级别上都不提供工资字段及其值,那么应该抛出一些错误,不应该通过REST Web服务处理请求;如果工资在任何一个级别上可用,那么应该接受该请求并由REST Web服务处理。
我目前正在使用javax.validation.constraints来进行JSON请求验证,是否有办法实现上述要求?
英文:
In below json request, you can see salary is available at 3 level
student level, trainee level and properties level
employee{
id :"123";
name : "ABC";
salary : 100;
college : "abcd..";
Trainees : {
id :"101";
name :"XYZ";
salary :50;
}
properties :{ // key value pair values
default.salary= 20
default.college=null
}
}
As salary is mandatory for my application, so salary should be available at least one level.
If salary field and its value is not available at all level then some error should be thrown and request should not be processed by rest webservice and if salary is available at any one level then request should be accepted and processed by rest webservice.
I am using currently javax.validation.constraints for json request validation, Is there any way to achieve above requirement?
答案1
得分: 1
如果您想使用javax bean验证,您需要定义一个自定义注释(针对您特定的用例,没有默认的注释),并使用您的自定义验证实现ConstraintValidator。您可以在此处查看示例:https://www.baeldung.com/javax-validation-method-constraints。
在这种情况下,这3个薪水字段应该是可为空的,您的验证逻辑应该验证至少有一个字段不为null。
英文:
If you want to use javax bean validations you will need to define a custom annotation (there is not a default one for you specific use case) and implement ConstraintValidator with your custom validation. You can see examples here: https://www.baeldung.com/javax-validation-method-constraints.
In this case the 3 salary fields should be nullable and your validation logic should verify that at least one of them is not null.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论