I have some YAML files, and I want to define a schema and then validate the YAML against the schema before trying to work with it in C#.
From my research there doesn't appear to be a schema language specific for YAML, but people use JSON Schema to validate YAML files. So that's what I tried.
The Yaml library I'm using (YamlDotNet) doesn't appear to be able to do schema validation, so I tried to do what I saw in some other examples. Convert the YAML to JSON then use Newtonsoft.Json to validate against my schema.
var schemaJson = File.ReadAllText(schemaPath);
var schema = Newtonsoft.Json.Schema.JSchema.Load(new JsonTextReader(new StringReader(schemaJson)));
var deserializer = new YamlDotNet.Serialization.Deserializer();
var data = deserializer.Deserialize(new StringReader(yaml));
var sb = new StringBuilder();
var sw = new StringWriter(sb);
var serializer = new Newtonsoft.Json.JsonSerializer();
serializer.Serialize(sw, data);
Newtonsoft.Json.Linq.JObject.Parse(sb.ToString()).Validate(schema);
The problem with this is when I deserialize the YAML, it stuffs the data into a Dictionary, and ultimately every value is a string. So when I serialize back to JSON all the values get wrapped in single quotes, and when I try to validate against my schema, anything that the schema says is an integer/number will fail.
e.g. This YAML:
name: John Doe
age: 27
will get converted to JSON something like this:
{
name: 'John Doe'
age: '27'
}
And when I try to validate against my JSON Schema that says age should be an integer that fails.