在 json 架构中使用“$ref”时出现 MalformedURLException

MalformedURLException when using "$ref" in json schema

我有一个 json 模式,它使用“$ref”(相对路径)引用另一个文件夹中存在的另一个 json 模式,我得到一个 "MalformedURLException".

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$ref": "#/definitions/Base",
  "definitions": {
    "Base": {
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "event": {
          "$ref": "com/artifacts/click/ClickSchema.json"
        },
        "arrival_timestamp": {
          "type": "integer",
          "minimum": 0.0
        }
      },
      "title": "Base"
    }
  }
}

而另一个文件夹中的点击模式如下:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "com/artifacts/click/ClickSchema.json",
  "Event": {
    "type": "object",
    "additionalProperties": false,
    "properties": {
      "sourceName": {
        "type": "string"
      }
    }
  }
}

有人可以帮忙吗。我正在使用 this 模式验证器。

A JSON 默认情况下,模式不知道它在文件中的位置,也不知道文件夹中的其他文件。

您使用的库似乎可以识别这一点,并建议您使用特殊的参考协议 (classpath) 轻松定位文件夹中的其他文件:

https://github.com/everit-org/json-schema#loading-from-the-classpath

As your schemas grow you will want to split that up into multiple source files and wire them with "$ref" references. If you want to store the schemas on the classpath (instead of eg. serving them through HTTP) then the recommended way is to use the classpath: protocol to make the schemas reference each other.

这不是 JSON 模式定义的内容。

更常见的方法是加载您打算使用的所有模式,并允许在您已有文件的地方进行本地解析。您使用的图书馆也支持这个:https://github.com/everit-org/json-schema#registering-schemas-by-uri

Sometimes it is useful to work with preloaded schemas, to which we assign an arbitary URI (maybe an uuid) instead of loading the schema through a URL. This can be done by assigning the schemas to a URI with the #registerSchemaByURI() method of the schema loader. Example:

SchemaLoader schemaLoader = SchemaLoader.builder()
        .registerSchemaByURI(new URI("urn:uuid:a773c7a2-1a13-4f6a-a70d-694befe0ce63"), aJSONObject)
        .registerSchemaByURI(new URI("http://example.org"), otherJSONObject)
        .schemaJson(jsonSchema)
        .resolutionScope("classpath://my/schemas/directory/")
        .build();

如果您打算让其他人使用您的模式,则还有其他注意事项。如果是这样,请发表评论,我会展开。