JSON请求验证必填字段 – Spring Boot REST API

huangapple go评论83阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年9月7日 22:56:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/63780007.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定