我正在尝试创建一个架构以确保外部提供的 JSON 具有以下形式:
{ Username: "Aaron" }
现在,我正在通过以下操作在 C# 中创建一个 Newtonsoft JSchema 对象:
var sch = new JSchema()
{
Type = JSchemaType.Object,
AllowAdditionalProperties = false,
Properties =
{
{
"Username",
new JSchema() { Type = JSchemaType.String }
}
}
};
这很接近,但不需要存在用户名属性。我尝试了以下方法:
var sch = new JSchema()
{
Type = JSchemaType.Object,
AllowAdditionalProperties = false,
Properties =
{
{
"Username",
new JSchema() { Type = JSchemaType.String }
}
},
Required = new List<string> { "Username" }
};
但是我得到:
Error CS0200 Property or indexer 'JSchema.Required' cannot be assigned to -- it is read only
事实上,文档指出 Required 属性是只读的:
https://www.newtonsoft.com/jsonschema/help/html/P_Newtonsoft_Json_Schema_JSchema_Required.htm
我错过了什么吗?为什么 Required 属性是只读的?我怎样才能要求用户名存在?
最佳答案
你不能设置Required
(只是一个get
),而是使用这个:
var sch = new JSchema()
{
Type = JSchemaType.Object,
AllowAdditionalProperties = false,
Properties =
{
{
"Username",
new JSchema() { Type = JSchemaType.String }
}
},
};
sch.Required.Add("Username");
关于c# - 如何使用 Json.NET.Schema 要求属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46852405/