Click or drag to resize
Json.NET Schema

Loading Schemas

 

Json.NET Schema represents schemas using the strongly typed JSchema object. JSchema is used whenever an application validates JSON.

Note Note

You do not need to specify the version of the JSON Schema you are loading. When loading an older schema (e.g. Draft 3) renamed schema properties and features will automatically be mapped to the latest version of JSON Schema.

Loading JSON Schemas

The simplest way to load a JSON Schema is from a string using Parse(String). This method parses the given JSON Schema string and loads it into a strongly typed JSchema object.

Parse JSON Schema string
string schemaJson = @"{
  'description': 'A person',
  'type': 'object',
  'properties':
  {
    'name': {'type':['string','null']},
    'hobbies': {
      'type': 'array',
      'items': {'type':'string'}
    }
  }
}";

JSchema schema = JSchema.Parse(schemaJson);

// validate JSON

Schemas can also be loaded directly from a JsonReader using Load(JsonReader). This is useful when loading a schema from a stream, such as loading from a file using a FileStream.

Load JSON Schema file
using (StreamReader file = File.OpenText(@"c:\person.json"))
using (JsonTextReader reader = new JsonTextReader(file))
{
    JSchema schema = JSchema.Load(reader);

    // validate JSON
}
Resolving externally referenced schemas

A JSON schema can reference external schemas. External references are typically a URL that points to where the external schema is publically hosted on the Internet. Json.NET Schema supports resolving external schemas with JSchemaResolver. The Parse and Load methods on JSchema each have overloads that take a schema resolver.

Json.NET Schema comes with two resolvers. JSchemaUrlResolver resolves URL schema references, downloading the URLs content and loading it as a schema. It supports the file:// and http:// protocols and requests from the WebRequest class.

Resolve an external schema over HTTP with JSchemaUrlResolver
// resolver will fetch 'http://schema.org/address.json' as the parent schema is loaded
JSchemaUrlResolver resolver = new JSchemaUrlResolver();

JSchema schema = JSchema.Parse(@"{
  'type': 'object',
  'properties': {
    'name': {'type':'string'},
    'addresses': {
      'type': 'array',
      'items': {'$ref': 'http://schema.org/address.json'}
    }
  }
}", resolver);

JToken json = JToken.Parse(@"{
  'name': 'James',
  'addresses': [
    {
      'line1': '99 Smithington Street',
      'line2': 'Real Town',
      'country': 'USA'
    }
  ]
}");

IList<string> errorMessages;
bool isValid = json.IsValid(schema, out errorMessages);

JSchemaUrlResolver can resolve relative references. To enable this scenario set the BaseUri property when loading the schema with the location you are loading it from. Relative references will be resolved using the base URI.

Resolve relative external schema references
// person.json, has a relative external schema reference 'address.json'
// --------
// {
//   'type': 'object',
//   'properties': {
//     'name': {'type':'string'},
//     'addresses': {
//       'type': 'array',
//       'items': {'$ref': 'address.json'}
//     }
//   }
// }
// --------

using (StreamReader file = File.OpenText(@"c:\person.json"))
using (JsonTextReader reader = new JsonTextReader(file))
{
    JSchemaUrlResolver resolver = new JSchemaUrlResolver();

    JSchema schema = JSchema.Load(reader, new JSchemaReaderSettings
    {
        Resolver = resolver,
        // where the schema is being loaded from
        // referenced 'address.json' schema will be loaded from disk at 'c:\address.json'
        BaseUri = new Uri(@"c:\person.json")
    });

    // validate JSON
}

The second resolver, JSchemaPreloadedResolver, allows you to add schema JSON to the resolver and associate it with an ID. The resolver will then load the schema JSON associated with a given ID when it is referenced.

Preloading is useful if you don't want to rely on a third-party website being available when resolving an external schema reference. Copying the schema file into your application and loading it yourself will ensure you never get a network related when loading it.

Resolve an external schema with JSchemaPreloadedResolver
string addressSchemaJson = @"{
  'type': 'object',
  'properties': {
    'line1': {'type': 'string'},
    'line2': {'type': 'string'},
    'country': {'type': 'string'}
  }
}";

// preload schema with ID 'http://schema.org/address.json'
JSchemaPreloadedResolver resolver = new JSchemaPreloadedResolver();
resolver.Add(new Uri("http://schema.org/address.json"), addressSchemaJson);

// the external ref will use the preloaded schema
JSchema schema = JSchema.Parse(@"{
  'type': 'object',
  'properties': {
    'name': {'type':'string'},
    'addresses': {
      'type': 'array',
      'items': {'$ref': 'http://schema.org/address.json'}
    }
  }
}", resolver);

JToken json = JToken.Parse(@"{
  'name': 'James',
  'addresses': [
    {
      'line1': '99 Smithington Street',
      'line2': 'Real Town',
      'Country': 'USA'
    }
  ]
}");

IList<string> errorMessages;
bool isValid = json.IsValid(schema, out errorMessages);
See Also