Newtonsoft.Json.Schema icon indicating copy to clipboard operation
Newtonsoft.Json.Schema copied to clipboard

JSchema.Load is not resolving references

Open markericson opened this issue 3 years ago • 1 comments
trafficstars

I started off simply trying to load a schema with references using JSchema.Load() and JSchema.Load() fails for every scenario with the error: "Unhandled exception. Newtonsoft.Json.Schema.JSchemaReaderException: Could not resolve schema reference './Common.schema.json#/definitions/Statement'."

I have tried the following three approaches without success.

  1. a simple call to JSchema.Load() without a JsonSchemaSettings.BaseUri hoping that the library would look at the current working directory to find the files
  2. providing a JSchemaReaderSettings to JSchema.Load() with a file scheme Uri to the path of my schema files (e.g. file://Users/.../testschema/ )
    • note: '...' is simply redacting a very long Uri
    • referenced file successfully loads in a browser using a full path file://Users/.../testschema/Common.schema.json
  3. hosting my testschema folder with a simple static web server and using the baseUri http://localhost:8080/
    • referenced file successfully loads in a browser using http://localhost:8080/Common.schema.json

Test.schema.json

{
  "schema": "https://json-schema.org/draft-4/schema",
  "title": "AccountInfo",
  "type": "object",
  "properties": {
    "accountNumber": {
      "type": "string"
    },
    "accountTerms": {
      "ref$": "Common.schema.json#/definitions/AccountsTypeEnum"
    },
    "stmtHistory": {
      "type": "array",
      "items": {
        "$ref": "Common.schema.json#/definitions/Statement"
      }
    }
  }
}

Common.schema.json

{
  "schema": "https://json-schema.org/draft-4/schema",
  "definitions": {
    "AccountTermsEnum": {
      "type": "string",
      "enum": ["Prepaid","Net10","Net30","5/15 Net 30","2/10 Net 30"]
    },
    "Statement": {
        "type": "object",
        "properties": {
          "createdDate": {"type": "string", "format": "date"},
          "totalBalance": {"type": "number"},
          "overdueBalance":  {"type": "number"}
        }
      }
  }
}

markericson avatar Oct 16 '22 20:10 markericson

I discovered that when using the file:// scheme URI as BaseUri, I needed to set JSchemaUrlResolver in the JSchemaReaderSettings.

markericson avatar Oct 16 '22 21:10 markericson