I created a JSON schema for my C# code using:
// Create JSON schema
var generator = new JSchemaGenerator();
var schema = generator.Generate(typeof(ConfigFileJsonSchema));
schema.Title = "PlexCleaner Schema";
schema.Description = "PlexCleaner config file JSON schema";
schema.SchemaVersion = new Uri("http://json-schema.org/draft-06/schema");
schema.Id = new Uri("https://raw.githubusercontent.com/ptr727/PlexCleaner/main/PlexCleaner.schema.json");
Console.WriteLine(schema);
I want to add a reference to this scheme whenever I create JSON output from my code:
private static string ToJson(ConfigFileJsonSchema settings)
{
return JsonConvert.SerializeObject(settings, Settings);
}
private static readonly JsonSerializerSettings Settings = new()
{
Formatting = Formatting.Indented,
StringEscapeHandling = StringEscapeHandling.EscapeNonAscii,
NullValueHandling = NullValueHandling.Ignore,
// We expect containers to be cleared before deserializing
// Make sure that collections are not read-only (get; set;) else deserialized values will be appended
// https://stackoverflow.com/questions/35482896/clear-collections-before-adding-items-when-populating-existing-objects
ObjectCreationHandling = ObjectCreationHandling.Replace
// TODO: Add TraceWriter to log to Serilog
};
How can I programmatically add the $schema
URI to the created JSON, not meaning creating schema on the fly, but something like this:
public class ConfigFileJsonSchemaBase
{
// Schema reference
[JsonProperty(PropertyName = "$schema", Order = -2)]
public string Schema { get; } = "https://raw.githubusercontent.com/ptr727/PlexCleaner/main/PlexCleaner.schema.json";
// Default to 0 if no value specified, and always write the version first
[DefaultValue(0)]
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate, Order = -2)]
public int SchemaVersion { get; set; } = ConfigFileJsonSchema.Version;
}
Without needing to add a $schema
entry to the class.
E.g. equivalent of:
schema.SchemaVersion = new Uri("http://json-schema.org/draft-06/schema");
There is a similar unanswered question: json serialization to refer schema