Click or drag to resize
Json.NETValidating JSON
 

With Json.NET Schema you can simply validate JSON in LINQ to JSON objects using the IsValid method. In more advanced scenarios you can validate JSON as you read and write it using JSchemaValidatingReader and JSchemaValidatingWriter

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, JSchema) method with the JSON Schema.

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

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

Validate JSON with IsValid
 1JSchema schema = JSchema.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// Invalid type. Expected String but got Null. Line 2, position 21.
11// Invalid type. Expected String but got Number. Line 3, position 51.
Detailed Validation Information

Detailed validation error information is accessable on ValidationError. It provides the line number, position and path of where the error occurred in the JSON document, the JSchema that failed validation, and any child errors that occured.

IsValid(JToken, JSchema, IListValidationError) and ValidationError both provide ValidationError for any errors.

Detailed validation information with ValidationError
 1string schemaJson = @"{
 2  'description': 'Collection of non-primary colors',
 3  'type': 'array',
 4  'items': {
 5    'allOf': [ { '$ref': '#/definitions/hexColor' } ],
 6    'not': {
 7      'enum': ['#FF0000','#00FF00','#0000FF']
 8    }
 9  },
10  'definitions': {
11    'hexColor': {
12      'type': 'string',
13      'pattern': '^#[A-Fa-f0-9]{6}$'
14    }
15  }
16}";
17
18JSchema schema = JSchema.Parse(schemaJson);
19
20JArray colors = JArray.Parse(@"[
21  '#DAA520', // goldenrod
22  '#FF69B4', // hot pink
23  '#0000FF', // blue
24  'Black'
25]");
26
27IList<ValidationError> errors;
28bool valid = colors.IsValid(schema, out errors);
29// Message - JSON is valid against schema from 'not'. Path '[2]', line 4, position 24.
30// SchemaId - #/items/0
31
32// Message - JSON does not match all schemas from 'allOf'. Invalid schema indexes: 0. Path '[3]', line 5, position 22.
33// SchemaId - #/items/0
34//   Message - String 'Black' does not match regex pattern '^#[A-Fa-f0-9]{6}$'. Path '[3]', line 5, position 22.
35//   SchemaId - #/definitions/hexColor
Validating when reading JSON

Internally IsValid uses JSchemaValidatingReader 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, JSchemaValidatingReader can be used with JsonSerializer to validate JSON while the object is being deserialized.

Validate JSON with JSchemaValidatingReader
 1string json = @"{
 2  'name': 'James',
 3  'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']
 4}";
 5
 6JsonTextReader reader = new JsonTextReader(new StringReader(json));
 7
 8JSchemaValidatingReader validatingReader = new JSchemaValidatingReader(reader);
 9validatingReader.Schema = JSchema.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);
Validating when writing JSON

JSON can also be validated while writing JSON with JSchemaValidatingWriter.

Validate JSON with JSchemaValidatingWriter
 1Person person = new Person
 2{
 3    Name = "James",
 4    Hobbies = new List<string>
 5    {
 6        ".NET", "Blogging", "Reading", "Xbox", "LOLCATS"
 7    }
 8};
 9
10StringWriter stringWriter = new StringWriter();
11JsonTextWriter writer = new JsonTextWriter(stringWriter);
12
13JSchemaValidatingWriter validatingWriter = new JSchemaValidatingWriter(writer);
14validatingWriter.Schema = JSchema.Parse(schemaJson);
15
16IList<string> messages = new List<string>();
17validatingWriter.ValidationEventHandler += (o, a) => messages.Add(a.Message);
18
19JsonSerializer serializer = new JsonSerializer();
20serializer.Serialize(validatingWriter, person);
See Also