Ajas Aju
Ajas Aju

Reputation: 755

JSON Schema Validator in C#

I have a class for Json Validation

public class RootObject
{
    [JsonProperty("Key", Required = Required.Always)]
    public string Key { get; set; }

    [JsonProperty("Value", Required = Required.Always)]
    public string Value { get; set; }

    [JsonProperty("Type", Required = Required.Always)]
    public string Type { get; set; }
}

And my requirement is to validate a JSON against my AttributeValue (format is below)

[{"Key":"Color","Value":"Pink","Type":"Simple"},{"Key":"Material","Value":"Silver","Type":"Simple"}]

My code is

if (objProductInfo.Products.AttributeValue != null)
{
    var generator = new JSchemaGenerator();
    JSchema schema = generator.Generate(typeof(List<RootObject>));
    JArray jsonArray = JArray.Parse(objProductInfo.Products.AttributeValue);
    bool isValidSchema = jsonArray.IsValid(schema);
    if (!isValidSchema)
    {
        objProductInfo.Products.AttributeValue = null;
    }
}

Here it's validating most cases but the issue is that if the format like below

 [{"Title":"Color","Key":"Color","Value":"Pink","Type":"Simple"}]

Two Issues am facing

  1. here we have one additional property is "Title".This is not a valid one but it's showing as valid.

  2. Even if forget to put Double quotes on any keys it will showing as valid eg: [{"Title":"Color","Key":"Color",Value:"Pink","Type":"Simple"}]

    Here Value has no quotes.

Upvotes: 1

Views: 2183

Answers (1)

vernou
vernou

Reputation: 7610

By default, the schema accept additional properties: https://www.newtonsoft.com/json/help/html/P_Newtonsoft_Json_Schema_JsonSchema_AllowAdditionalProperties.htm

You can override this setting in the schema instance :

public static void NotAllowAdditional(JSchema schema)
{
    schema.AllowAdditionalProperties = false;
    schema.AllowAdditionalItems = false;
    foreach (var child in schema.Items)
    {
        NotAllowAdditionalProperties(child);
    }
}

Upvotes: 1

Related Questions