问题描述
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"}]
面临两个问题
解决方法
默认情况下,架构接受其他属性: 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);
}
}