【问题标题】:Spring boot - class validation not working on REST APISpring Boot - 类验证不适用于 REST API
【发布时间】:2020-05-06 20:02:19
【问题描述】:

我有以下 REST API:

@ResponseBody
    @PostMapping(path = "/configureSegment")
    public ResponseEntity<ResultData> configureSegment(@RequestParam() String segment,
                                                       @RequestBody @Valid CloudSegmentConfig segmentConfig
                                                        )  {

CloudSegmentConfig:

@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 参数,而它没有,尽管我向它添加了所有可能的注释..

有什么想法吗?

【问题讨论】:

    标签: java spring-boot jackson


    【解决方案1】:

    TelemetryConfig telemetryConfig 上使用@Valid 注解,在TelemetryConfig 类的字段上不需要使用@Valid。

    @Valid
    TelemetryConfig telemetryConfig;
    

    对于枚举子集验证,您可以创建一个带有注释的客户验证器并使用它。 关于这个Validating a Subset of an Enum的一个很好的文档@

    【讨论】:

    • 谢谢!我看到错误显示的是真实的类名而不是杰克逊的名字,例如"telemetryConfig.isEnabled: Please provide a valid isEnabled",而不是txConfig,有什么办法解决这个问题吗?
    • 也许你正在寻找这个stackoverflow.com/questions/41717866/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-09
    • 1970-01-01
    • 1970-01-01
    • 2020-09-27
    • 2020-09-08
    • 2018-07-04
    相关资源
    最近更新 更多