问题
I want to deserialize this YAML with YAMLDotNet.
It have sequence and nested mapping.
- data.yml
people:
- name: "John"
age: 20
- name: "Michael"
age: 21
- name: "William"
age: 22
network:
address: "192.168.1.1"
port: 1234
param:
paramNumber: 10
paramString: "text data"
paramBool: true
This is my code. But, It can't compile. I would like to know the following two things.
- How to define class to decerialize nested mapping?
- How to access it?
- Print Deserialized Data
DeserializedObject obj = YamlImporter.Deserialize("data.yml");
foreach(var people in obj.people)
{
Console.WriteLine(people.name);
Console.WriteLine(people.age);
}
Console.WriteLine(obj.network["address"]);
Console.WriteLine(obj.network["port"]);
/* how to access param? */
- Deserializer Code (YAMLDotNet)
public class YamlImporter
{
public static DeserializedObject Deserialize(string yamlName)
{
StreamReader sr = new StreamReader(yamlName);
string text = sr.ReadToEnd();
var input = new StringReader(text);
var deserializer = new DeserializerBuilder().WithNamingConvention(CamelCaseNamingConvention.Instance).Build();
DeserializedObject deserializeObject = deserializer.Deserialize<DeserializedObject>(input); /* compile error */
return deserializeObject;
}
}
public class DeserializedObject
{
public List<People> people { get; set; }
public class People
{
public string name { get; set; }
public int age { get; set; }
}
public Dictionary<string, Network> network { get; set; }
public class Network
{
public string address { get; set; }
public int port { get; set; }
public Dictionary<string, Param> param { get; set; }
}
public class Param
{
public int paramNumber { get; set; }
public string paramString { get; set; }
public bool paramBool { get; set; }
}
}
Thanks,
回答1:
@AluanHaddad's advice helped me solve my problem. Thanks,
// How to access params? //
Console.WriteLine(obj.network.param.paramNumber);
Console.WriteLine(obj.network.param.paramString);
Console.WriteLine(obj.network.param.paramBool);
//public Dictionary<string, Network> network { get; set; }
public Network network { get; set; }
public class Network
{
public string address { get; set; }
public int port { get; set; }
//public Dictionary<string, Param> param { get; set; }
public Param param { get; set; }
}
来源:https://stackoverflow.com/questions/63388702/how-to-deserialize-yaml-with-yamldotnet