How to reference external files with JSON.net?

泄露秘密 提交于 2019-12-06 07:17:31

Json.NET Schema has much improved support for resolving external references.

Read more here: http://www.newtonsoft.com/jsonschema/help/html/LoadingSchemas.htm

One idea I have is to skim through the schema, and if there are any references to external files, to parse those with a common JsonSchemaResolver

Yes, you need to know which schemas your schema depends on, parse those first and add them to a JsonSchemaResolver. The schemas will be resolved using their IDs.

Here's an example (using draft-03 syntax):

var baseSchema = JsonSchema.Parse(@"
{
  ""$schema"": ""http://json-schema.org/draft-03/schema#"",
  ""id"": ""http://mycompany/base-schema#"",
  ""type"": ""object"",

  ""properties"": {
    ""firstName"": { ""type"": ""string"", ""required"": true}
  }
}
");

var resolver = new JsonSchemaResolver
    {
        LoadedSchemas = {baseSchema}
    };

var derivedSchema = JsonSchema.Parse(@"
{
  ""$schema"": ""http://json-schema.org/draft-03/schema#"",
  ""id"": ""http://mycompany/derived-schema#"",
  ""type"": ""object"",

  ""extends"":{ ""$ref"": ""http://mycompany/base-schema#""},

  ""properties"": {
    ""lastName"": { ""type"": ""string"", ""required"": true}
  }
}
", resolver);

Fiddle: https://dotnetfiddle.net/g1nFew

I think the problem may be that you have relative URI's in those $ref items, but no id properties to establish a base URI. You may be able to resolve your problem by adding id="<absolute-url>"in the outermost context establishing where those external files can be retrieved from.

See section 7 of http://json-schema.org/latest/json-schema-core.html

P.S. In your measure item, I notice you have both a $ref and description values. The json-reference internet draft says Any members other than "$ref" in a JSON Reference object SHALL be ignored. It probably doesn't do any harm, but could be surprising if someone was to expect that value to override the description in the external file.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!