如何在 JSON 模式中使用 oneOf 来验证 POST 和 PATCH 请求?
How to use oneOf in JSON schema to validate both POST and PATCH requests?
目前我们使用的架构文件包含 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 文件,但我们的技术经理宁愿将它们放在一个地方。
oneOf
和 anyOf
子句可用于对条件约束进行建模。以下模式将根据 id
属性 的存在验证补丁或 post 模式:
{
"oneOf" : [{
"$ref" : "/post_request_schema#"
}, {
"allOf" : [{
"$ref" : "/patch_request_schema#"
}, {
"required" : ["id"]
}
]
}
]
}
目前我们使用的架构文件包含 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 文件,但我们的技术经理宁愿将它们放在一个地方。
oneOf
和 anyOf
子句可用于对条件约束进行建模。以下模式将根据 id
属性 的存在验证补丁或 post 模式:
{
"oneOf" : [{
"$ref" : "/post_request_schema#"
}, {
"allOf" : [{
"$ref" : "/patch_request_schema#"
}, {
"required" : ["id"]
}
]
}
]
}