I have the following yaml structure:
TestPaySignService:
Test:
TestString:
settings-key: TestStringValue
types:
- type1
- type2
TestString2:
settings-key: TestStringValue2
types:
- type1
- type2
I want to parse this yaml and store only "settings-key" and "types" together in c# collection, for example List, like the following:
[
{
name: TestStringValue,
types: ["type1", "type2"]
},
{
name: TestStringValue2,
types: ["type1", "type2"]
}
]
I've followed the follwin question and tried the accepted answer's code, but as it seems it's obsolete for now: Deserialize a YAML "Table" of data
PS my yaml schema changes every time, but "settings-key" and "types" are always contained, so I want to create something like "dynamic parser"
You can deserialize the yaml to a dynamic object then walk a bit. Something like the following:
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);
}
Output
[{
"settings-key": "TestStringValue",
"types": [
"type1",
"type2"
]
},
{
"settings-key": "TestStringValue2",
"types": [
"type1",
"type2"
]
}]
If you need to use TestString, you should deserialize it into an object.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.