Using JSON Schema

I’ve been having to do some development lately around a project that requires strictly formatted data to be applied against a validated schema.  In looking at options, I evaluated JSON-Schema and XSD.  When looking around for which is better the results came back with neither side one is super superior to the other.  However, since this is for a REST service, I thought let’s go with JSON.

What I like about JSON-Schema is that it’s very quick to get up and running with.  The complete specification is available here and you can read through it in about an hour.  Over the next few posts I’ll highlight some of the key features of the schema and what I really like about it.

To get started, binding an already established file to a JSON-Schema is relatively simple all you need to do is read the actual JSON and JSON-Schema files and then bind them together.

//Load the Schema (from the local file stystem)
string schemaJson = File.ReadAllText("json-schema.json");
string dataJson = File.ReadAllText("sample-submission.json");

//Determine if both the Schema and Json file are valid documents.
JSchema schema = JSchema.Parse(schemaJson);
JObject data = JObject.Parse(dataJson);

You can check to see if the binding is applied correctly by checking to see if your data object is valid and whether there are any errors in the binding protocol.

IList<string> validationErrors;
bool valid = data.IsValid(schema,out validationErrors);

if (!valid)
{
Console.WriteLine("Is Valid: " + valid.ToString());
Console.WriteLine("Validation Errors Found.");

foreach (string item in validationErrors)
{
Console.WriteLine("Error: " + item);
}
}
else
{
Console.WriteLine("Is Valid: " + valid.ToString());
}

Of interesting note with JSON-Schema, all the errors in the file are returned when an error is found, not just the first one it finds when processing the information.

Post A Reply

%d bloggers like this: