This sample validates JSON while deserializing an object using JsonValidatingReader.

Sample

Types Copy imageCopy
1public class Person
2{
3    public string Name { get; set; }
4    public IList<string> Hobbies { get; set; }
5}
Usage Copy imageCopy
 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
13string json = @"{
14  'name': 'James',
15  'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']
16}";
17
18JsonTextReader reader = new JsonTextReader(new StringReader(json));
19
20JsonValidatingReader validatingReader = new JsonValidatingReader(reader);
21validatingReader.Schema = JsonSchema.Parse(schemaJson);
22
23IList<string> messages = new List<string>();
24validatingReader.ValidationEventHandler += (o, a) => messages.Add(a.Message);
25
26JsonSerializer serializer = new JsonSerializer();
27Person p = serializer.Deserialize<Person>(validatingReader);
28
29Console.WriteLine(p.Name);
30// James
31
32bool isValid = (messages.Count == 0);
33
34Console.WriteLine(isValid);
35// true