Search code examples
c#json.netjsonschema

How to require a property using Json.NET.Schema?


I am trying to create a schema to ensure that outside-supplied JSON is of the following form:

{ Username: "Aaron" }

Right now, I'm creating a Newtonsoft JSchema object in C# by doing:

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

This is close, but does not require the presence of the Username property. I've tried the following:

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

But I get:

Error CS0200 Property or indexer 'JSchema.Required' cannot be assigned to -- it is read only

And indeed, the documentation notes that the Required property is read-only:

https://www.newtonsoft.com/jsonschema/help/html/P_Newtonsoft_Json_Schema_JSchema_Required.htm

Am I missing something? Why would the Required property be read-only? How can I require the presence of Username?


Solution

  • You can't set Required (is only a get) use instead this:

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