【问题标题】:MalformedURLException when using "$ref" in json schema在 json 模式中使用“$ref”时出现 MalformedURLException
【发布时间】:2019-08-11 23:12:59
【问题描述】:

我有一个 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 架构验证器。

【问题讨论】:

    标签: json schema jsonschema json-schema-validator


    【解决方案1】:

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

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

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

    随着架构的增长,您会希望将其拆分为多个 源文件并将它们与“$ref”引用联系起来。如果你想 将模式存储在类路径上(而不是例如为它们提供服务 通过 HTTP)那么推荐的方法是使用类路径: 协议使模式相互引用。

    这不是 JSON Schema 定义的东西。

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

    有时使用预加载的模式很有用,我们对此 分配一个任意 URI(可能是一个 uuid)而不是加载架构 通过一个 URL。这可以通过将模式分配给 URI 来完成 架构加载器的 #registerSchemaByURI() 方法。示例:

    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();
    

    如果您打算让其他人使用您的架构,还有其他注意事项。如果是这种情况,请发表评论,我会展开。

    【讨论】:

    • 谢谢。您能否也添加其他注意事项。
    • 会的。如果我在星期二之前还没有这样做,请再次发表评论! =]
    • 您能否添加其他注意事项?
    • 抱歉回复缓慢。如果您打算让其他人使用您的架构,您要么必须确保他们知道加载目录的所有架构(因为这通常不是标准的)。这并不总是图书馆支持的东西(尽管它们确实应该)。或者,如果可以,将您的 $id 和引用更改为可通过 Internet 访问的真实 URL。这是更常见的支持。
    猜你喜欢
    • 2015-08-10
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    • 2012-09-22
    • 1970-01-01
    • 1970-01-01
    • 2018-04-13
    • 2014-07-08
    相关资源
    最近更新 更多