使用YamlDotNet反序列化FontAwesome Yaml

本文关键字:Yaml FontAwesome 反序列化 YamlDotNet 使用 | 更新日期: 2024-10-19 07:46:57

我有一个Yaml文件:https://raw.githubusercontent.com/FortAwesome/Font-Awesome/master/src/icons.yml

还有一类:

public class IconSearch
{
    public string Name { get; set; }
    public string ClassName { get; set; }
    public IEnumerable<string> Filters { get; set; }
}

你能告诉我如何将yaml反序列化为对象的IEnumerable吗?

我希望这样的东西能起作用,但它返回null——我猜这是因为我的一个属性不是根节点(图标)。相反,我正在尝试序列化根的子项?

var input = new StringReader(reply);
var yaml = new YamlStream();
yaml.Load(input);
var icons = deserializer.Deserialize<IconSearch>(input);

使用YamlDotNet反序列化FontAwesome Yaml

您试图反序列化到的类似乎缺少属性。我把yaml转换成json再转换成csharp,这就是生成的类:

public class Rootobject
{
public Icon[] icons { get; set; }
}
public class Icon
{
public string[] categories { get; set; }
public object created { get; set; }
public string[] filter { get; set; }
public string id { get; set; }
public string name { get; set; }
public string unicode { get; set; }
public string[] aliases { get; set; }
public string[] label { get; set; }
public string[] code { get; set; }
public string url { get; set; }
}

使用的资源:
YAML到JSON在线
JSON到CSHARP(我在visual studio中使用了Paste special)

使用它来反序列化

var icons = deserializer.Deserialize<RootObject>(input);

更新
我已经注释掉了您用于创建YamlStream的行,因为它不是必需的(它将读取器定位在流的末尾而不是开头,这可以解释为什么您早些时候得到null)。您的主要方法如下所示并且有效。我还修复了Antoine提到的错误

public static void Main()
{
    string filePath = "https://raw.githubusercontent.com/FortAwesome/Font-Awesome/master/src/icons.yml";
    WebClient client = new WebClient();
    string reply = client.DownloadString(filePath);
    var input = new StringReader(reply);
    //var yamlStream = new YamlStream();
    //yamlStream.Load(input);
    Deserializer deserializer = new Deserializer();
    //var icons = deserializer.Deserialize<IconSearch>(input);
    //Testing my own implementation
    //if (icons == null)
    //    Console.WriteLine("Icons is null");
    //Testing Shekhar's suggestion
    var root = deserializer.Deserialize<Rootobject>(input);
    if (root == null)
        Console.WriteLine("Root is null");
}