JsonSchemaGenerator未将字段设置为required = false

atc*_*way 5 c# json json.net jsonschema

我在一系列模型中使用JsonSchemaGeneratorfrom JSON.NET来将相应的JSON模式输出到如下的字典中.

JsonSchemaGenerator generator = new JsonSchemaGenerator()
{
    UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName,
};
List<Type> modelTypes = Assembly.GetExecutingAssembly()
    .GetTypes()
    .ToList()
    .Where(t => t.Namespace == "MyApp.Models")
    .ToList();

foreach (Type type in modelTypes)
{
    JsonSchema schema = generator.Generate(type, jsonSchemaResolver, false);
    schemaDictionary.Add(type, schema);
}
Run Code Online (Sandbox Code Playgroud)

除了为required属性设置的值外,这项工作正常.不管我怎么装饰模特属性,字段总是被示为"required":true如下所示:

"FirstName": {
   "required": true,
   "type": "string"
}
Run Code Online (Sandbox Code Playgroud)

但是,在代码中我的模型是这样装饰的:

[JsonProperty(Required = Required.Default)]
public string FirstName { get; set; }
Run Code Online (Sandbox Code Playgroud)

纵观Json.Net 文档,设置Required.Default应导致的财产被需要的模式:

"默认- 0 -是资产,所需的默认状态."

有什么想法,我正在做错误,需要更改,以便FirstName在架构中输出属性"required": false?我希望有产生和手部按摩所有这些模式的.

Ili*_*mov 7

Required该枚举值可控制的财产有:NULL值是否被允许.要控制"required"json模式中的 属性,意味着json字符串是否必须包含实际属性,您需要在生成模式时使用DefaultValueHandlingNullValueHandling枚举.可以说我们有以下课程:

public class Person
{
        [JsonProperty(Required = Required.Default)]
        public string FirstName { get; set; }    
}
Run Code Online (Sandbox Code Playgroud)

使用JSON.NET为此类生成的模式如下所示:

{
    "id": "MyApp.Models.Person",
    "type": "object",
    "properties": {
        "FirstName": {
            "required": true,
            "type": [
                "string",
                "null"
            ]
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

此模式指示json字符串必须具有该属性,FirstName并且此属性允许具有空值.

通过更改Required属性Default,Always我们将获得以下架构:

{
    "id": "MyApp.Models.Person",
    "type": "object",
    "properties": {
        "FirstName": {
            "required": true,
            "type": "string"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

此模式指示json字符串必须具有该属性,FirstName并且此属性不允许具有空值.

要获得所需内容,您需要包含DefaultValueHandlingNullValueHandling枚举.像这样的东西:

public class Person
{
    [JsonProperty(Required = Required.Default, DefaultValueHandling = DefaultValueHandling.Ignore)]
    public string FirstName { get; set; }    
}
Run Code Online (Sandbox Code Playgroud)

此类中生成的模式如下所示:

{
    "id": "MyApp.Models.Person",
    "type": "object",
    "properties": {
        "FirstName": {
            "type": [
                "string",
                "null"
            ]
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

此模式指示FirstNamejson字符串中不需要该属性,但如果它存在,则它可能具有null值.如果使用DefaultValueHandling.IgnoreAndPopulate枚举值或切换到NullValueHandling属性而不是DefaultValueHandling属性并将其值设置为,则可以实现相同的效果NullValueHandling.Ignore.