Newtonsoft.Json.Schema
Newtonsoft.Json.Schema copied to clipboard
JSchema.Load is not resolving references
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.
- 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
- 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
- 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"}
}
}
}
}
I discovered that when using the file:// scheme URI as BaseUri, I needed to set JSchemaUrlResolver in the JSchemaReaderSettings.