Deserializing YAML using YamlDotNet when the root node of each object is named using it's ID?

自作多情 提交于 2019-12-11 04:15:27

问题


I'm using C# and I have a YAML file I want to deserialize.

I've looked at using YamlDotNet, and it looks like it's pretty decent, but I can't find how to handle this situation.

The YAML objects take the following format:

1:
    id: 1
    name: foo
2:
    id: 2
    name: foo

Ideally this would be:

(EDIT: Changed ideal format as per Anthon's comment.)

- id: 1
  name: foo
- id: 2
  name: foo

But it's not ... oh well.

I can of course revert to doing everything much more manually, by looping over each node and manually creating the data object instances, but it seems like there should still be a way to have the ease of use from YamlDotNet while handling this annoying data structure.

I'm open to suggestions for other YAML parsing libraries in .net.


回答1:


I found the answer in another SO question: Seeking guidance reading .yaml files with C#

By deserializing to Dictionary<int, Item> I can successfully handle this data structure.

deserializer.Deserialize<Dictionary<int, Item>>(textReader);



回答2:


If you use a list, as your edit, you can deserialize that file easily using code similar to this:

class MyObject {
    public int Id { get; set; }
    public string Name { get; set; }
}

var deserializer = new DeserializerBuilder()
     .WithNamingConvention(new CamelCaseNamingConvention())
     .Build();

var result = deserializer.Deserialize<List<MyObject>>(File.OpenText("myfile.yml"));

Note: I am typing on a phone and can't test the code. It should be mostly correct but I haven't tested it.



来源:https://stackoverflow.com/questions/41146291/deserializing-yaml-using-yamldotnet-when-the-root-node-of-each-object-is-named-u

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