如何使用JsonSchema.NET要求一个属性?

时间:2017-10-20 15:27:47

标签: c# json.net jsonschema

我正在尝试创建一个模式,以确保外部提供的JSON具有以下形式:

{ Username: "Aaron" }

现在,我正在通过以下方式在C#中创建一个Newtonsoft JSchema对象:

var sch = new JSchema()
{
    Type = JSchemaType.Object,
    AllowAdditionalProperties = false,
    Properties =
    {
        {
            "Username",
            new JSchema() { Type = JSchemaType.String }
        }
    }
};

这很接近,但不需要存在Username属性。我尝试了以下内容:

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属性是只读的?我如何要求存在用户名?

2 个答案:

答案 0 :(得分:3)

您无法设置Required(只是get)而不是:

var sch = new JSchema()
{
    Type = JSchemaType.Object,
    AllowAdditionalProperties = false,
    Properties =
    {
        {
            "Username",
            new JSchema() { Type = JSchemaType.String }
        }
    },
};
sch.Required.Add("Username");

答案 1 :(得分:1)

您可以将C# Collection Initialization syntax与只读列表属性like so结合使用:

var sch = new JSchema()
{
    Type = JSchemaType.Object,
    AllowAdditionalProperties = false,
    Properties =
    {
        {
            "Username",
            new JSchema() { Type = JSchemaType.String }
        }
    },
    Required = // <-- here!
    {
        "Username"
    }
};