Aaron G
Aaron G

Reputation: 33

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?

Upvotes: 3

Views: 1925

Answers (2)

Dai
Dai

Reputation: 155400

The answer from @PinBack from 2017 is incorrect: you can use C# Collection Initialization syntax with read-only list properties, like so:

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

Upvotes: 3

PinBack
PinBack

Reputation: 2564

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");

Upvotes: 4

Related Questions