Click or drag to resize
Json.NET Schema

Validate JSON with JSchemaValidatingWriter

 

This sample validates JSON while serializing an object using JSchemaValidatingWriter.

Sample
Types
public class Person
{
    public string Name { get; set; }
    public IList<string> Hobbies { get; set; }
}
Usage
string schemaJson = @"{
  'description': 'A person',
  'type': 'object',
  'properties': {
    'name': {'type':'string'},
    'hobbies': {
      'type': 'array',
      'items': {'type':'string'}
    }
  }
}";

Person p = new Person
{
    Name = "James",
    Hobbies = new List<string>
    {
        ".NET", "Blogging", "Reading", "Xbox", "LOLCATS"
    }
};

StringWriter stringWriter = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(stringWriter);
writer.Formatting = Formatting.Indented;

JSchemaValidatingWriter validatingWriter = new JSchemaValidatingWriter(writer);
validatingWriter.Schema = JSchema.Parse(schemaJson);

IList<string> messages = new List<string>();
validatingWriter.ValidationEventHandler += (o, a) => messages.Add(a.Message);

JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(validatingWriter, p);

Console.WriteLine(stringWriter);
// {
//   "Name": "James",
//   "Hobbies": [
//     ".NET",
//     "Blogging",
//     "Reading",
//     "Xbox",
//     "LOLCATS"
//   ]
// }

bool isValid = (messages.Count == 0);

Console.WriteLine(isValid);
// true