How to deserialize YAML with YAMLDotNet?

微笑、不失礼 提交于 2021-01-29 06:32:03

问题


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.

  1. How to define class to decerialize nested mapping?
  2. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!