W Anders
W Anders

Reputation: 13

Accessing key from YamlDotNet deserializer

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?

Upvotes: 1

Views: 1665

Answers (1)

Robert Reinhart
Robert Reinhart

Reputation: 517

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();
            }
        }

Upvotes: 2

Related Questions