OpenAPI规范在yaml或json格式和解析在c#



我如何在yaml或json格式中采用大型OpenAPI规范并将其扁平化以生成c#中的摘要,标签,路径,httpMethod ?

假设使用JObject SelectTokens,但我无法弄清楚语法。

string json = File.ReadAllText ("spec.json");
JObject array = JObject.Parse(json);
array.SelectTokens("paths").Dump();

下面是一个json规范示例

{
"paths": {
"/entities/{id}": {
"get": {
"summary": "Get Entity",
"tags": [
"Things"
]
},
"put": {
"summary": "Update Entity",
"tags": [
"Things"
]
}
},
"/otherEntities/{id}": {
"get": {
"summary": "Get Other",
"tags": [
"Others"
]
},
"put": {
"summary": "Update Other",
"tags": [
"Others"
]
}
}
}
}

我想要:

"Get Entity", "Things", "/entities/{id}", "get"
"Update Entity", "Things", "/entities/{id}", "put"
"Get Other", "Others", "/otherEntities/{id}", "get"
"Update Other", "Others", "/otherEntities/{id}", "put"
  1. 迭代paths

    1.1。为pathsJObject转换JObjectDictionary

  2. 1.1迭代KeyValuePair

    2.1。获取密钥为path

    2.1。将字典的值转换为methodKvp

  3. 2.2迭代KeyValuePair

    3.1。获取密钥为method

    3.2。从标记"summary"中获取summary

    3.3。从标记"tags"中获取数组的第一个值的标记。

    3.4。将提取的值添加到列表。

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Linq;
List<List<string>> result = new ();
foreach (JObject pathObj in array.SelectTokens("paths").AsJEnumerable())
{           
Dictionary<string, JObject> pathDict = pathObj.ToObject<Dictionary<string, JObject>>(); 
foreach (KeyValuePair<string, JObject> pathKvp in pathDict)
{
var path = pathKvp.Key;
var methodDict = pathKvp.Value.ToObject<Dictionary<string, JObject>>();
foreach (KeyValuePair<string, JObject> methodKvp in methodDict)
{
string method = methodKvp.Key;
string summary = (string)methodKvp.Value.SelectToken("summary");
string tag = (string)methodKvp.Value.SelectToken("tags").AsEnumerable().First();
result.Add(new List<string> { summary, tag, path, method });
}
}       
}

示例。net Fiddle

相关内容

  • 没有找到相关文章

最新更新