C# 如何使用Json.NET.Schema要求属性?
我正在尝试创建一个模式,以确保外部提供的JSON采用以下形式:C# 如何使用Json.NET.Schema要求属性?,c#,json.net,jsonschema,C#,Json.net,Jsonschema,我正在尝试创建一个模式,以确保外部提供的JSON采用以下形式: { Username: "Aaron" } 现在,我正在C#中创建一个Newtonsoft JSchema对象,方法是: var sch = new JSchema() { Type = JSchemaType.Object, AllowAdditionalProperties = false, Properties = { { "Username",
{ 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" }
};
事实上,文档指出所需的属性是只读的:
我错过什么了吗?为什么所需的属性是只读的?我如何要求用户名的存在?您不能设置
必需的
(仅是获取
)请使用以下选项:
var sch = new JSchema()
{
Type = JSchemaType.Object,
AllowAdditionalProperties = false,
Properties =
{
{
"Username",
new JSchema() { Type = JSchemaType.String }
}
},
};
sch.Required.Add("Username");
2017年@PinBack的回答不正确:您可以与只读列表属性一起使用:
var sch=new JSchema()
{
Type=JSchemaType.Object,
AllowAdditionalProperties=false,
性质=
{
{
“用户名”,
新的JSchema(){Type=JSchemaType.String}
}
},
Required=//JSchema
是否有任何重载的构造函数?或者您可以尝试在需要的属性上使用[JsonProperty(Required=Required.Always)]
属性。您可以通过执行Required={“UserName”}将C#列表初始化语法与只读列表属性一起使用
。C#编译器将其更改为必需。在后台添加(“用户名”)
。
var sch = new JSchema()
{
Type = JSchemaType.Object,
AllowAdditionalProperties = false,
Properties =
{
{
"Username",
new JSchema() { Type = JSchemaType.String }
}
},
};
sch.Required.Add("Username");
var sch = new JSchema()
{
Type = JSchemaType.Object,
AllowAdditionalProperties = false,
Properties =
{
{
"Username",
new JSchema() { Type = JSchemaType.String }
}
},
Required = // <-- here!
{
"Username"
}
};