作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有以下 REST API:
@ResponseBody
@PostMapping(path = "/configureSegment")
public ResponseEntity<ResultData> configureSegment(@RequestParam() String segment,
@RequestBody @Valid CloudSegmentConfig segmentConfig
) {
云段配置:
@JsonProperty(value="txConfig", required = true)
@NotNull(message="Please provide a valid txConfig")
TelemetryConfig telemetryConfig;
@JsonProperty(value="rxConfig")
ExternalSourcePpdkConfig externalSourcePpdkConfig = new ExternalSourcePpdkConfig(true);
遥测配置:
public class TelemetryConfig {
static Gson gson = new Gson();
@JsonProperty(value="location", required = true)
@Valid
@NotNull(message="Please provide a valid location")
Location location;
@Valid
@JsonProperty(value="isEnabled", required = true)
@NotNull(message="Please provide a valid isEnabled")
Boolean isEnabled;
地点:
static public enum Location {
US("usa"),
EU("europe"),
CANADA("canada"),
ASIA("asia");
private String name;
private Location(String s) {
this.name = s;
}
private String getName() {
return this.name;
}
}
当我尝试发送以下 JSON 时:
{
"txConfig": {
"location": "asdsad"
}
}
API 返回空响应 400 错误请求,而我希望它验证该位置是该类的 ENUM 之一。我还希望它能够验证 isEnable 参数,尽管我向它添加了所有可能的注释,但它没有验证。
有什么想法吗?
最佳答案
在TelemetryConfig telemetryConfig
上使用@Valid注解,不需要在TelemetryConfig
类的字段上使用@Valid。
@Valid
TelemetryConfig telemetryConfig;
对于枚举子集验证,您可以创建带有注释的客户 validator 并使用它。关于此的好文档 Validating a Subset of an Enum
关于java - Spring boot - 类验证不适用于 REST API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61634384/
我是一名优秀的程序员,十分优秀!