1

I'm trying to deserialize a YAML file from a source that I don't control where some of the files have numerical keys.

Example:

0:
    name: Category1
    published: true
1:
    name: Category2
    published: false

For my purposes, the numerical key is important to store since that's how other datasets will refer to the data.

Example:

3573:
    name: Item1
    category: 0
89475:
    name: Item2
    category: 1

Is there any way to access the key from YAMLDotNet's Deserializer to feed the class?

W Anders
  • 13
  • 6

1 Answers1

2

I smell eve online... o7 ... I've also been there and done that so here is your answer. Use the document root node as a (YamlMappingNode) and iterate the children (a key value pair). The entry key will be the categoryID and the entry value will be the category data.

        YamlMappingNode mapping = (YamlMappingNode)yaml.Documents[0].RootNode;
        foreach (var entry in mapping.Children)
        {
            int categoryID = Int32.Parse(entry.Key.ToString());
            YamlMappingNode params = (YamlMappingNode)entry.Value;
            foreach (var param in params.Children)
            {
                string paramName = param.Key.ToString();
                // Assign value to parameter.
                if(paramName == "name")
                    name = param.Value.ToString();
            }
        }
Robert Reinhart
  • 507
  • 4
  • 10
  • o7 Good nose. Trying not to rely on Steve too much. I'll try it out and let you know if I run into any problems. Thanks! – W Anders Dec 04 '16 at 22:27