2

I need to deserialize the following YAML to my custom type. YamlAlias attribute seems to be obsolete, so I replaced it with YamlMember. It fails on deserializing the following YAML with the below exception:

    host:
      properties:
        mem_size: 2048  MB

YamlDotNet.Core.YamlException : (Line: 21, Col: 13, Idx: 524) - (Line: 21, Col: 13, Idx: 524): Exception during deserialization ----> System.Runtime.Serialization.SerializationException : Property 'mem_size' not found on type 'Toscana.Domain.HostProperties'.

public class Host
{
    public HostProperties Properties { get; set; }
}

public class HostProperties
{
    [YamlMember(typeof(DigitalStorage))]
    public string MemSize { get; set; }
}
Boris Modylevsky
  • 3,029
  • 1
  • 26
  • 42

1 Answers1

4

The Alias is a property of the YamlMemberAttribute class, it's not in the constructor. Now, I don't know how your DigitalStorage class looks like and whether a string will be successfully deserialized into it (I doubt it), but since your question is to add an alias, this is how you do it:

public class HostProperties
{
    [YamlMember(typeof(DigitalStorage), Alias = "mem_size")]
    public string MemSize { get; set; }
}
Asbjørn Ulsberg
  • 8,721
  • 3
  • 45
  • 61
  • How do you set an alies for the `HostProperties` class? In XML I would use `[XmlRoot(ElementName = "HP")]`? – MrCalvin Apr 09 '20 at 07:48
  • @MrCalvin, I don't think you can decorate classes themselves, only instances of classes. The root class won't be visible in the serialized YAML, only the properties within it. So to give `HostProperties` an alias you would have to decorate the `Properties` property within the `Host` class with `YamlMember(Alias = "properties")`. – Asbjørn Ulsberg Apr 14 '20 at 08:28