如何使用 Json.NET.Schema 要求 属性?
How to require a property using Json.NET.Schema?
我正在尝试创建一个架构以确保外部提供的 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");
@PinBack 2017 年的回答不正确:您可以 使用C# Collection Initialization syntax with read-only list properties, :
var sch = new JSchema()
{
Type = JSchemaType.Object,
AllowAdditionalProperties = false,
Properties =
{
{
"Username",
new JSchema() { Type = JSchemaType.String }
}
},
Required = // <-- here!
{
"Username"
}
};
我正在尝试创建一个架构以确保外部提供的 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");
@PinBack 2017 年的回答不正确:您可以 使用C# Collection Initialization syntax with read-only list properties,
var sch = new JSchema()
{
Type = JSchemaType.Object,
AllowAdditionalProperties = false,
Properties =
{
{
"Username",
new JSchema() { Type = JSchemaType.String }
}
},
Required = // <-- here!
{
"Username"
}
};