.netcore获得swagger对象信息(解析swagger的json文件)

以下代码未经测试,谨慎使用!!!

 

var reader = new Microsoft.OpenApi.Readers.OpenApiStringReader();
var doc = reader.Read(System.IO.File.ReadAllText(_webHostEnvironment.WebRootPath + "/a.json"), out var diagnostic);
var doc1 = _swaggerGenerator.GetSwagger(version); //1. 根据指定版本获取指定版本的json对象。

 

foreach (var item in openApiDocument.Paths)
{

 

foreach (var operation in item.Value.Operations)
{
var methodName = operation.Key.ToString();
var tag = string.Join(Environment.NewLine, operation.Value.Tags.Select(c => c.Name.RemoveMarkdown()));
var summary = operation.Value.Summary.RemoveMarkdown();
var description = operation.Value.Description.RemoveMarkdown();

 

/*返回值*/
var res = operation.Value.Responses; 
var res1 = operation.Value.Responses?["200"]?.Content["application/json"]?.Schema?.Properties["Rows"]?.Items?.Reference?.Id;  //返回对象的类名

 

var resClassName = operation.Value.Responses?["200"]?.Content["application/json"]?.Schema?.Properties["Rows"]?.Items?.Reference?.Id;
var has = openApiDocument.Components.Schemas.ContainsKey(resClassName);
if (has)
{
var resCls = openApiDocument.Components.Schemas[resClassName];
var des = resCls.Description;
foreach (var pro in resCls.Properties)
{
var str = $"{pro.Key} {pro.Value.Type} {pro.Value.Description}";
}
}

 

if (operation.Value.RequestBody != null)
{
var requestBody = $"描述:{operation.Value.RequestBody.Description + Environment.NewLine}";
requestBody += $"类型:{string.Join(',', operation.Value.RequestBody.Content.Keys) + Environment.NewLine}";
reportModel.RequestType = requestBody;
}
if (operation.Value.Parameters?.Count > 0)
{
reportModel.ParameterItems.AddRange(
operation.Value.Parameters.Select(parameter => new ParametersItem
{
ParaName = parameter.Name,
ParaType = parameter.In?.ToString() ?? "",
ParaRequired = parameter.Required,
ParaDescription = parameter.Description
})
);
var parameters = JsonSerializer.Serialize(reportModel.ParameterItems, jsonOptions);
}
}

 

}

 

https://github.com/ricoisme/swagger2document

posted @ 2024-03-25 16:09  Ace001  阅读(92)  评论(0编辑  收藏  举报