0

我有一个 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);
4

1 回答 1

2

您尝试反序列化的类似乎缺少属性。我绕过了将 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 to JSON online
JSON to 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");
}
于 2015-03-06T16:39:14.847 回答