You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

继承IDocumentFilter后,如何为Swagger数组属性添加子属性?

给Swagger中数组类型的Schema循环绑定子属性的方法

嗨,这事儿其实核心是要搞清楚数组类型的Schema结构——因为你定义的Parent是array类型,它本身的子属性其实是定义在items字段里的,这个items才是数组中每个元素的结构模板。接下来我给你一步步演示怎么循环添加子属性:

步骤1:获取并配置Parent的数组元素Schema

首先得先拿到你已经创建好的Parent Schema,然后给它指定items(也就是数组里每个元素的Schema),之后我们就在这个items的properties里循环加子属性就行。

示例代码如下:

// 获取JsonData下的Parent Schema
var parentArraySchema = swagDoc.properties["JsonData"].properties["Parent"];

// 创建数组元素的Schema模板,这就是Parent数组里每个对象的结构
var parentItemSchema = new Schema();
// 把这个模板绑定到Parent数组的items属性上
parentArraySchema.items = parentItemSchema;

步骤2:循环添加子属性

接下来你可以定义一个要添加的属性列表(比如用字典存属性名和对应的类型),然后遍历这个列表,逐个把属性添加到parentItemSchema的properties里:

// 定义要添加的子属性集合,key是属性名,value是Swagger支持的类型(integer/string/object等)
var childProps = new Dictionary<string, string>
{
    {"Id", "integer"},
    {"ParentName", "string"},
    {"CreateTime", "string"},
    {"IsActive", "boolean"}
};

// 循环遍历,给数组元素Schema添加子属性
foreach (var prop in childProps)
{
    parentItemSchema.properties.Add(prop.Key, new Schema { type = prop.Value });
}

进阶:如果子属性是嵌套结构/数组

要是你需要添加的子属性本身也是对象或者数组,也可以在循环里进一步配置。比如想加一个Children子属性,它本身也是数组类型:

foreach (var prop in childProps)
{
    var childSchema = new Schema { type = prop.Value };
    
    // 针对特定属性做嵌套配置
    if (prop.Key == "Children")
    {
        // 把Children设为数组,并且定义它的元素结构
        childSchema.type = "array";
        childSchema.items = new Schema
        {
            properties = new Dictionary<string, Schema>
            {
                {"ChildId", new Schema { type = "integer" }},
                {"ChildName", new Schema { type = "string" }}
            }
        };
    }
    
    parentItemSchema.properties.Add(prop.Key, childSchema);
}

这样操作之后,你的Swagger文档里JsonData下的Parent数组,就会清晰展示每个元素包含你循环添加的所有子属性啦~

内容的提问来源于stack exchange,提问作者memz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:32:33