首页 > 解决方案 > Swagger 中的自定义模型对象数组

问题描述

在由 IDocumentFilter 驱动的类中

我可以浏览 swagger 文档并在下面添加新属性

SwaggerDocument 为我提供了一个定义。

然后我创建一个新属性并将数组分配为模式,例如;

swagDoc.properties["JsonData"].properties.Add("Parent", new Schema() { type = "array" });

它允许文档在 JsonData 文档下面有一个数组属性

然后我想打开一个循环来绑定父模式下的子属性,例如;

for (int i = 1; i < 10; i++) 
{
    swagDoc.properties["JsonData"].properties["Parent"].properties.Add(
        "Child"+i.ToString(), 
        new Schema() { type = "string" }); 
}      

我期待 Swagger 请求输入中有一个 Json 对象;

{
    "JsonData": { 
        "request_rejected_date": "string", 
        "report_delivered_date": "string", 
        "report_cancelled_date": "string", 
        "Parent": [ { 
            "child1": "string", 
            "child2": "string", 
            "child3": "string", 
            "child4": "string", 
            "child5": "string", 
            "child6": "string", 
            "child7": "string",
            "child8": "string", 
            "child9": "string" 
        } ] 
    } 
}

我没有要绑定的已定义类,我确实在 Swagger 中动态生成模型

但是,上面的代码不会产生类似的东西——我怎样才能做到这一点?

谢谢

标签: c#swaggerswagger-ui

解决方案


在玩过这个物体之后,显然这是可行的方法(:

swagDoc.properties["JsonData"].properties["Parent"].items = new Schema() { properties = new Dictionary<string, Schema>() };

 var schemaChild = new Schema() { description = "Child1", type = "string" };

swagDoc.properties["JsonData"].properties["Parent"].items.properties.Add("child1", schemaChild);       

推荐阅读