Click or drag to resize
Json.NETLoading 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
 1string schemaJson = @"{
 2  'description': 'A person',
 3  'type': 'object',
 4  'properties':
 5  {
 6    'name': {'type':['string','null']},
 7    'hobbies': {
 8      'type': 'array',
 9      'items': {'type':'string'}
10    }
11  }
12}";
13
14JSchema schema = JSchema.Parse(schemaJson);
15
16// 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
1using (StreamReader file = File.OpenText(@"c:\person.json"))
2using (JsonTextReader reader = new JsonTextReader(file))
3{
4    JSchema schema = JSchema.Load(reader);
5
6    // validate JSON
7}
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
 1// resolver will fetch 'http://schema.org/address.json' as the parent schema is loaded
 2JSchemaUrlResolver resolver = new JSchemaUrlResolver();
 3
 4JSchema schema = JSchema.Parse(@"{
 5  'type': 'object',
 6  'properties': {
 7    'name': {'type':'string'},
 8    'addresses': {
 9      'type': 'array',
10      'items': {'$ref': 'http://schema.org/address.json'}
11    }
12  }
13}", resolver);
14
15JToken json = JToken.Parse(@"{
16  'name': 'James',
17  'addresses': [
18    {
19      'line1': '99 Smithington Street',
20      'line2': 'Real Town',
21      'country': 'USA'
22    }
23  ]
24}");
25
26IList<string> errorMessages;
27bool 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
 1// person.json, has a relative external schema reference 'address.json'
 2// --------
 3// {
 4//   'type': 'object',
 5//   'properties': {
 6//     'name': {'type':'string'},
 7//     'addresses': {
 8//       'type': 'array',
 9//       'items': {'$ref': 'address.json'}
10//     }
11//   }
12// }
13// --------
14
15using (StreamReader file = File.OpenText(@"c:\person.json"))
16using (JsonTextReader reader = new JsonTextReader(file))
17{
18    JSchemaUrlResolver resolver = new JSchemaUrlResolver();
19
20    JSchema schema = JSchema.Load(reader, new JSchemaReaderSettings
21    {
22        Resolver = resolver,
23        // where the schema is being loaded from
24        // referenced 'address.json' schema will be loaded from disk at 'c:\address.json'
25        BaseUri = new Uri(@"c:\person.json")
26    });
27
28    // validate JSON
29}

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
 1string addressSchemaJson = @"{
 2  'type': 'object',
 3  'properties': {
 4    'line1': {'type': 'string'},
 5    'line2': {'type': 'string'},
 6    'country': {'type': 'string'}
 7  }
 8}";
 9
10// preload schema with ID 'http://schema.org/address.json'
11JSchemaPreloadedResolver resolver = new JSchemaPreloadedResolver();
12resolver.Add(new Uri("http://schema.org/address.json"), addressSchemaJson);
13
14// the external ref will use the preloaded schema
15JSchema schema = JSchema.Parse(@"{
16  'type': 'object',
17  'properties': {
18    'name': {'type':'string'},
19    'addresses': {
20      'type': 'array',
21      'items': {'$ref': 'http://schema.org/address.json'}
22    }
23  }
24}", resolver);
25
26JToken json = JToken.Parse(@"{
27  'name': 'James',
28  'addresses': [
29    {
30      'line1': '99 Smithington Street',
31      'line2': 'Real Town',
32      'Country': 'USA'
33    }
34  ]
35}");
36
37IList<string> errorMessages;
38bool isValid = json.IsValid(schema, out errorMessages);
See Also