gpt4 book ai didi

java - Spring boot - 类验证不适用于 REST API

转载 作者:行者123 更新时间:2023-12-01 16:53:38 24 4
gpt4 key购买 nike

我有以下 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com