MrCalvin
MrCalvin

Reputation: 1825

Set name of key/class using YamlDotNet or SharpYaml

I'm trying to (de)serialize following YAML using YamlDotNet or SharpYaml:

network:
  IF1:
    gateway4: 10.1.0.1        
    addresses:
      - 10.1.0.10/24
      - 10.1.0.20/24
  IF2:
    gateway4: 10.2.0.1        
    addresses:
      - 10.2.0.10/24
      - 10.2.0.20/24

I've have this C# class:

public class NetworkConfig
{
    public class Network
    {
        //[ClassName]
        public string NetworkName { get; set; }

        public List<Interface> Interfaces;

        public class Interface
        {
            //[ClassName]
            public string InterfaceName { get; set; }
            public string gateway4;
            public List<String> addresses;
        }
    }
}

Instantiation:

var NetworkCfg = new NetworkConfig();
var Network = new NetworkConfig.Network();
Network.NetworkName = "network";
Network.Interfaces = new List<NetworkConfig.Network.Interface> {
    new NetworkConfig.Network.Interface
    {
        InterfaceName = "IF1",
        gateway4 = "10.1.0.1",
        addresses = new List<string> { "10.1.0.10/24", "10.1.0.20/24"}
    },
    new NetworkConfig.Network.Interface
    {
        InterfaceName = "IF2",
        gateway4 = "10.2.0.1",
        addresses = new List<string> { "10.2.0.10/24", "10.2.0.20/24"}
    }
};

How do I name the key/class Network and Interface?

One solution I could think of would be an attribute for a property, something like [ClassName] but I haven't been able to find one.

Upvotes: 0

Views: 688

Answers (1)

flyx
flyx

Reputation: 39768

Your problem is that your YAML structure does not match your class structure. The YAML structure you show is basically

Dictionary<string, Dictionary<string, Interface>>

without InterfaceName in Interface. As you can see, the name of your network and interfaces are on another level than the objects they name, hence you cannot simply load them into the object via annotation.

You have two options:

  • Load the YAML into the type described above, and then post-process it to your type structure.
  • Implement a custom constructor and representer for your type hierarchy that (de)serializes it into the YAML structure you want.

The latter option is somewhat faster, but I'd say it's not worth the effort.

Upvotes: 1

Related Questions