C#中的JSON模式验证器

问题描述

我有一个用于Json验证的类

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; }
}

我的要求是针对我的AttributeValue(格式如下)验证JSON

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

我的代码

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;
    }
}

这里可以验证大多数情况,但问题是,如果格式如下所示

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

面临两个问题

  1. 在这里,我们还有一个附加属性“ Title”。这不是有效属性,但 显示为有效。

  2. 即使忘记在任何键上加上双引号,它也会显示为有效 例如: [{“标题”:“颜色”,“键”:“颜色”,值:“粉红色”,“类型”:“简单”}]

    这里Value没有引号。

解决方法

默认情况下,架构接受其他属性: https://www.newtonsoft.com/json/help/html/P_Newtonsoft_Json_Schema_JsonSchema_AllowAdditionalProperties.htm

您可以在模式实例中覆盖此设置:

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