1

我正在使用 justinrainbow/json-schema 类来根据模式验证数据。但是我收到此错误:

Media type application/schema+json expected

我可以尝试在 nginx 中为我的所有 json 文件更改 ContentType,但这没有意义。

另一种方法是将库中的常量更改为“application/json”(因为我的服务器正在为 json 文件提供服务)。同样,更改源也不行。

有没有办法将此作为参数传递给 justinrainbow/json-schema 类?

https://github.com/justinrainbow/json-schema

4

2 回答 2

0

我找不到解决方案,因为网络上没有 schema+json 的内容类型。

只需将 justinrainbow/json-schema/src/JsonSchema/Validator.php 中的 SCHEMA_MEDIA_TYPE 替换为“application/json”即可。

您还可以通过本地路径提供文件,而不是通过 url。

于 2015-02-18T13:04:33.917 回答
0

现在该库还支持“json/application”,但它会在其他内容类型上引发错误。

为避免这种情况,您可以扩展默认的“JsonSchema\Uri\UriRetriever”并覆盖“ confirmMediaType() ”:

class MyUriRetriever extends JsonSchema\Uri\UriRetriever {

    public function confirmMediaType($uriRetriever, $uri) {
        return;
    }
}

$retriever = new \MyUriRetriever();

$refResolver = new JsonSchema\SchemaStorage($retriever);
$schema = $refResolver->resolveRef($schema);

$validator = new JsonSchema\Validator(new JsonSchema\Constraints\Factory($refResolver));
$validator->check($data, $schema);

$data:来自 API 的 json 解码响应

$schema:架构的 url

在针对他们的架构测试其他方的 API 时,我多次遇到同样的问题。他们通常不会为他们的模式发送正确的“Content-Type”标头,而且他们可能需要很长时间才能更改它。

更新:能够从验证中排除端点

您可以使用UriRetriever:addInvalidContentTypeEndpoint()

$retriever = new UriRetriever();
$retriever->addInvalidContentTypeEndpoint('http://example.com/car/list');
于 2016-12-27T09:16:11.767 回答