gpt4 book ai didi

c# - 如何获取 JSON.NET JSchema 生成器以在 JSON 模式中呈现 additionalProperties 属性

转载 作者:太空宇宙 更新时间:2023-11-03 12:14:21 24 4
gpt4 key购买 nike

我正在使用 JSON.NET JSchema 生成器创建基于用数据注释属性修饰的类的模式。我正在使用这样的生成器:

var generator = new JSchemaGenerator();
generator.ContractResolver = new CamelCasePropertyNamesContractResolver();
generator.SchemaIdGenerationHandling = SchemaIdGenerationHandling.TypeName;
var schema = generator.Generate(typeof(myType));
string jsonSchema = schema.ToString();

这会生成一个示例架构,如:

{
"$id": "myType",
"definitions": {
"mySubType" : {
"$id": "mySubType",
"type": [
"object",
"null"
],
"properties": {
"name": {
"type: "string"
}
},
"required": [
"name"
]
}
},
"type": "object",
"properties": {
"name": {
"type": "string"
},
"details": {
"$ref": "mySubType"
}
},
"required": [
"name",
"details"
]
}

希望能够为myTypemySubType 生成包含附加属性属性的架构,如下所示:

{
"$id": "myType",
"definitions": {
"mySubType" : {
"$id": "mySubType",
"type": [
"object",
"null"
],
"properties": {
"name": {
"type: "string"
}
},
"required": [
"name"
],
"additionalProperties": false
}
},
"type": "object",
"properties": {
"name": {
"type": "string"
},
"details": {
"$ref": "mySubClass"
}
},
"required": [
"name",
"details"
],
"additionalProperties": false
}

如何使用 JSchema 生成器生成这样的模式?

是否有类级别的数据注释属性可以执行此操作?

最佳答案

有点晚了,但我今天为此苦苦挣扎..

void Main()
{
var generator = new JSchemaGenerator();
generator.ContractResolver = new CamelCasePropertyNamesContractResolver();
generator.SchemaIdGenerationHandling = SchemaIdGenerationHandling.TypeName;
var schema = generator.Generate(typeof(myType));
RejectAdditionalProperties(schema);
string jsonSchema = schema.ToString();
}

static void RejectAdditionalProperties(JSchema schema)
{
schema.AllowAdditionalProperties = false;
foreach(var s in schema.Properties.Values) RejectAdditionalProperties(s);
}

关于c# - 如何获取 JSON.NET JSchema 生成器以在 JSON 模式中呈现 additionalProperties 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50498881/

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