3

目前我们正在使用一个包含oneOf的模式文件,其中包含2 个模式:一个用于 PATCH 请求,一个用于 POST 请求。在 Java 代码中,我们检查 id 在请求中是否可用,然后我们检查 oneOf 部分中的第一个模式是否有任何错误消息。

像这样的东西:

        processingReport.iterator().forEachRemaining(processingMessage -> {
        JsonNode json = processingMessage.asJson();

        JSONObject reports = new JSONObject(json.get("reports").toString());
        logger.debug("Schema validation: {}", reports.toString());
        //Seems always has 2 reports.
        String reportIdentifier = isCreate ? "/properties/data/oneOf/0" : "/properties/data/oneOf/1";
        JSONArray errorsArray = new JSONArray(reports.get(reportIdentifier).toString());

        //Do something with the error here

    });

但这对我来说似乎不合适。有没有办法在模式本身中管理它,所以当 id 可用时,它会从 oneOf 中选择正确的模式,或者可能有更好的方法来做到这一点?

我知道一种选择是拥有不同的 json 文件,但我们的技术经理宁愿将它们保留在一个地方。

4

1 回答 1

2

oneOfandanyOf子句可用于对条件约束进行建模。以下模式将根据id属性的存在来验证补丁或发布模式:

{
    "oneOf" : [{
            "$ref" : "/post_request_schema#"
        }, {
            "allOf" : [{
                    "$ref" : "/patch_request_schema#"
                }, {
                    "required" : ["id"]
                }
            ]
        }
    ]
}
于 2016-08-04T07:38:09.970 回答