eraxillan
eraxillan

Reputation: 1620

How to specify "any name" field for Yaml.Net

I am trying to deserialize the specified piece of YAML, using Yaml.Net library:

version: '5'
infoFiles:
   <relative path to file 1>: <int number>
   <relative path to file 2>: <int number>
   ...
   <relative path to file N>: <int number>

E.g.:

dir1/file1 : '1'
dir2/dir3/file2 : '5"

To deserialize any YAML file we need to describe it using C# classes:

var deserializer = new Deserializer( null, new CamelCaseNamingConvention() );
var myYamlData = ( Yaml )deserializer.Deserialize( textReader, typeof( MyYamlDataClass ) );

...
class MyYamlDataClass
{
    public int Version;
    public **what type to use here?**[] InfoFiles;
}

So, how to describe the InfoFiles field in Yaml.Net terms?
The problem is what i don't know the field names on compile time.
So, YamlAlias probably will not help.

P.S. See https://dotnetfiddle.net/HD2JXM to see example of structure description

Upvotes: 0

Views: 815

Answers (1)

Ondrej Svejdar
Ondrej Svejdar

Reputation: 22084

You can use Dictionary<string,int>, also the fields should be properties. So the final class should look like:

public class MyYamlDataClass
{
  public int Version { get; set; }
  public Dictionary<string, int> InfoFiles { get; set; }
}

Also note you don't have to specify deserialization type at all. In this case deserializer reverts to Dictionary<object,object>.

var foo = @"version: '5'
infoFiles:
  patha: 1
  pathb: 2
  pathc: 3";

var deserializer = new Deserializer(null, new CamelCaseNamingConvention());
var bar = (Dictionary<object,object>)deserializer.Deserialize(new StringReader(foo));    

Upvotes: 2

Related Questions