gpt4 book ai didi

c# - JsonSchemaGenerator 未将字段设置为 required = false

转载 作者:太空狗 更新时间:2023-10-29 22:58:43 26 4
gpt4 key购买 nike

我正在使用 JSON.NET 中的 JsonSchemaGenerator 针对一系列模型将相应的 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);
}

除了为 required 属性设置的值外,它工作正常。无论我如何装饰模型属性,字段总是显示为"required":true,如下所示:

"FirstName": {
"required": true,
"type": "string"
}

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

[JsonProperty(Required = Required.Default)]
public string FirstName { get; set; }

查看 Json.Net documentation ,设置为 Required.Default 应该导致架构中需要该属性:

"Default - 0 - The property is not required. The default state."

关于我做错了什么并且需要更改以便 FirstName 属性在架构中输出为 "required": false 的任何想法?我不想必须生成并手动按摩所有这些模式。

最佳答案

Required 枚举控制属性可以有哪些值:是否允许空值。要控制 json 模式中的 "required" 属性,即 json 字符串是否必须包含实际属性,您需要使用 DefaultValueHandlingNullValueHandling 生成模式时的枚举。假设我们有以下类(class):

public class Person
{
[JsonProperty(Required = Required.Default)]
public string FirstName { get; set; }
}

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

{
"id": "MyApp.Models.Person",
"type": "object",
"properties": {
"FirstName": {
"required": true,
"type": [
"string",
"null"
]
}
}
}

此架构指示 json 字符串必须具有属性 FirstName 并且允许此属性具有空值。

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

{
"id": "MyApp.Models.Person",
"type": "object",
"properties": {
"FirstName": {
"required": true,
"type": "string"
}
}
}

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

要获得所需内容,您需要包含 DefaultValueHandlingNullValueHandling 枚举。像这样:

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

从此类生成的架构如下所示:

{
"id": "MyApp.Models.Person",
"type": "object",
"properties": {
"FirstName": {
"type": [
"string",
"null"
]
}
}
}

此架构表明 json 字符串中不需要 FirstName 属性,但如果存在,它可能具有空值。如果您使用 DefaultValueHandling.IgnoreAndPopulate 枚举值,或者如果您切换到 NullValueHandling 属性而不是 DefaultValueHandling 属性并设置其NullValueHandling.Ignore 的值。

关于c# - JsonSchemaGenerator 未将字段设置为 required = false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25430783/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com