简体   繁体   中英

MalformedURLException when using "$ref" in json schema

I have a json schema which refers to another json schema present in another folder using "$ref" (relative path) and i get a "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"
    }
  }
}

And the click schema in another folder is as follows:

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

Can someone please help. I am using this schema validator.

A JSON Schema knows nothing about where it sits in a file, and nothing about the other fils in a folder, by default.

It looks like the library you're using recognises this, and suggests you use a special reference protocol ( classpath ) to target other files in a folder with ease:

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.

This isn't something defined by JSON Schema.

The more common approach is to load in all the schemas you intend to use, and allow for local resolution where you have the files already. The library you're using also supports this: 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();

There are additional considerations if you intend for your schemas to be used by others. If that's the case, do comment, and I'll expand.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM