【问题标题】:How to require a property using Json.NET.Schema?如何使用 Json.NET.Schema 要求属性?
【发布时间】:2018-04-01 19:41:13
【问题描述】:

我正在尝试创建一个架构以确保外部提供的 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 属性是只读的?如何要求提供用户名?

【问题讨论】:

  • JSchema 是否有任何重载的构造函数?
  • 或者你可以尝试在你想要的属性上使用[JsonProperty(Required = Required.Always)] 属性
  • 您可以通过 Required = { "UserName" } 将 C# 列表初始化语法与只读列表属性一起使用。 C# 编译器会将其更改为 Required.Add("UserName") behind-the-scenes。

标签: c# json.net jsonschema


【解决方案1】:

你不能设置Required(只是get)改用这个:

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

【讨论】:

    【解决方案2】:

    @PinBack 2017 年的答案不正确:您可以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"
        }
    };
    

    【讨论】:

      猜你喜欢
      • 2020-12-02
      • 1970-01-01
      • 1970-01-01
      • 2023-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-27
      • 2012-11-25
      相关资源
      最近更新 更多