1

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.

1 Answer 1

1

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);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I have given the AllowAdditionalProperties and AllowAdditionalItems false,But still it's not fixed.
You need set AllowAdditional* in all schema tree, like in the example method NotAllowAdditional when foreach (var child in schema.Items).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.