我具有以下yaml结构:
TestPaySignService:
Test:
TestString:
settings-key: TestStringValue
types:
- type1
- type2
TestString2:
settings-key: TestStringValue2
types:
- type1
- type2
我想解析此Yaml,并仅将“ settings-key”和“ types”一起存储在c#集合中,例如List,如下所示:
[
{
name: TestStringValue,
types: ["type1", "type2"]
},
{
name: TestStringValue2,
types: ["type1", "type2"]
}
]
我遵循了follwin问题并尝试了接受的答案的代码,但目前看来它已经过时了:Deserialize a YAML "Table" of data
P.S。我的yaml模式每次都会更改,但是始终包含“设置键”和“类型”,因此我想创建类似“动态解析器”的
答案 0 :(得分:0)
您可以将Yaml反序列化为动态对象,然后再走一点。类似于以下内容:
public static void Main()
{
var r = new StringReader(@"TestPaySignService:
Test:
TestString:
settings-key: TestStringValue
types:
- type1
- type2
TestString2:
settings-key: TestStringValue2
types:
- type1
- type2");
var deserializer = new Deserializer();
var yamlObject = deserializer.Deserialize<dynamic>(r)["TestPaySignService"]["Test"].Values;
// just to print the json
var serializer = new JsonSerializer();
serializer.Serialize(Console.Out, yamlObject);
}
输出
[{
"settings-key": "TestStringValue",
"types": [
"type1",
"type2"
]
},
{
"settings-key": "TestStringValue2",
"types": [
"type1",
"type2"
]
}]
如果需要使用TestString,则应将其反序列化为对象。