Click or drag to resize
Json.NETValidating JSON with JSON Schema
 

Json.NET supports the JSON Schema standard via the JsonSchema and JsonValidatingReader classes. It sits under the Newtonsoft.Json.Schema namespace.

JSON Schema is used to validate the structure and data types of a piece of JSON, similar to XML Schema for XML. You can read more about JSON Schema at json-schema.org

Caution note Caution

Obsolete. JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.

Validating with JSON Schema

The simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then use the IsValid(JToken, JsonSchema) method with the JSON Schema.

Validate JSON with IsValid
 1string schemaJson = @"{
 2  'description': 'A person',
 3  'type': 'object',
 4  'properties':
 5  {
 6    'name': {'type':'string'},
 7    'hobbies': {
 8      'type': 'array',
 9      'items': {'type':'string'}
10    }
11  }
12}";
13
14JsonSchema schema = JsonSchema.Parse(schemaJson);
15
16JObject person = JObject.Parse(@"{
17  'name': 'James',
18  'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']
19}");
20
21bool valid = person.IsValid(schema);
22// true

To get validation error messages, use the IsValid(JToken, JsonSchema, IListString) or Validate(JToken, JsonSchema, ValidationEventHandler) overloads.

Validate JSON with IsValid
 1JsonSchema schema = JsonSchema.Parse(schemaJson);
 2
 3JObject person = JObject.Parse(@"{
 4  'name': null,
 5  'hobbies': ['Invalid content', 0.123456789]
 6}");
 7
 8IList<string> messages;
 9bool valid = person.IsValid(schema, out messages);
10// false
11// Invalid type. Expected String but got Null. Line 2, position 21.
12// Invalid type. Expected String but got Float. Line 3, position 51.

Internally IsValid uses JsonValidatingReader to perform the JSON Schema validation. To skip the overhead of loading JSON into a JObject/JArray, validating the JSON, and then deserializing the JSON into a class, JsonValidatingReader can be used with JsonSerializer to validate JSON while the object is being deserialized.

Validate JSON with JsonValidatingReader
 1string json = @"{
 2  'name': 'James',
 3  'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']
 4}";
 5
 6JsonTextReader reader = new JsonTextReader(new StringReader(json));
 7
 8JsonValidatingReader validatingReader = new JsonValidatingReader(reader);
 9validatingReader.Schema = JsonSchema.Parse(schemaJson);
10
11IList<string> messages = new List<string>();
12validatingReader.ValidationEventHandler += (o, a) => messages.Add(a.Message);
13
14JsonSerializer serializer = new JsonSerializer();
15Person p = serializer.Deserialize<Person>(validatingReader);
Creating JSON Schemas

The simplest way to get a JsonSchema object is to load it from a string or a file.

Creating JSON Schemas from strings or files
 1// load from a string
 2JsonSchema schema1 = JsonSchema.Parse(@"{'type':'object'}");
 3
 4// load from a file
 5using (TextReader reader = File.OpenText(@"c:\schema\Person.json"))
 6{
 7    JsonSchema schema2 = JsonSchema.Read(new JsonTextReader(reader));
 8
 9    // do stuff
10}

It is also possible to create JsonSchema objects in code.

Create new JSON Schemas in code
 1JsonSchema schema = new JsonSchema();
 2schema.Type = JsonSchemaType.Object;
 3schema.Properties = new Dictionary<string, JsonSchema>
 4{
 5    { "name", new JsonSchema { Type = JsonSchemaType.String } },
 6    {
 7        "hobbies", new JsonSchema
 8        {
 9            Type = JsonSchemaType.Array,
10            Items = new List<JsonSchema> { new JsonSchema { Type = JsonSchemaType.String } }
11        }
12    },
13};
14
15JObject person = JObject.Parse(@"{
16  'name': 'James',
17  'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']
18}");
19
20bool valid = person.IsValid(schema);
21// true
See Also