【问题标题】:How to specify alias on YamlMember in YamlDotNet?如何在 YamlDotNet 中的 YamlMember 上指定别名?
【发布时间】:2016-06-05 07:45:06
【问题描述】:

我需要将以下 YAML 反序列化为我的自定义类型。 YamlAlias 属性似乎已经过时,所以我将其替换为 YamlMember。它在反序列化以下 YAML 时失败,但有以下异常:

    host:
      properties:
        mem_size: 2048  MB

YamlDotNet.Core.YamlException : (Line: 21, Col: 13, Idx: 524) - (Line: 21, Col: 13, Idx: 524): 反序列化期间出现异常 ----> System.Runtime.Serialization.SerializationException:在类型“Toscana.Domain.HostProperties”上找不到属性“mem_size”。

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

public class HostProperties
{
    [YamlMember(typeof(DigitalStorage))]
    public string MemSize { get; set; }
}

【问题讨论】:

    标签: c# yaml yamldotnet


    【解决方案1】:

    AliasYamlMemberAttribute 类的属性,它不在构造函数中。现在,我不知道您的 DigitalStorage 类的外观以及 string 是否会成功反序列化到其中(我对此表示怀疑),但是由于您的问题是添加别名,因此您是这样做的:

    public class HostProperties
    {
        [YamlMember(typeof(DigitalStorage), Alias = "mem_size")]
        public string MemSize { get; set; }
    }
    

    【讨论】:

    • 如何为HostProperties 类设置别名?在 XML 中我会使用 [XmlRoot(ElementName = "HP")]?
    • @MrCalvin,我认为你不能自己装饰类,只能装饰类的实例。根类在序列化的 YAML 中不可见,只有其中的属性。因此,要给 HostProperties 一个别名,您必须使用 YamlMember(Alias = "properties") 装饰 Host 类中的 Properties 属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-15
    • 2011-07-06
    • 1970-01-01
    • 1970-01-01
    • 2014-09-13
    • 1970-01-01
    相关资源
    最近更新 更多