2017-03-04 337 views
1

我刚开始与Yaml合作,并且非常感激一些输入。我正在创建一个YAML并试图将其去除到现有的C#类中。 现有的C#类:将Yaml反序列化为c#对象

[System.Xml.Serialization.XmlIncludeAttribute(typeof(FooType))] 

    public partial class BarType { 

     private int barVariable; 

     public Int Bar { 
     get { 
      return this.barVariable; 
     } 
     set { 
      this.barVariable = value; 
     } 
    } 


    } 

    public partial class FooType : BarType { 

     private string fooVariable; 
     public string Foo { 
     get { 
      return this.fooVariable; 
     } 
     set { 
      this.fooVariable = value; 
     } 
    } 


[System.Xml.Serialization.XmlRootAttribute("HeadType", Namespace="xyz", IsNullable=false)] 

public partial class HeadType { 

    private BarType[] barTypesField; 

    [System.Xml.Serialization.XmlArrayItemAttribute("FooService", typeof(FooType), IsNullable=false)] 

     public BarType[] BarTypes { 
      get { 
       return this.barTypesField; 
       } 
      set { 
       this.barTypesField = value; 
       } 
      } 

现在我有一个YAML,

HeadType: 
    - Bar: 0 
    - Bar: 29 

当我尝试deserialze上述YAML,我没有得到任何错误。

但是,当我将Yaml更改为类似下面的内容时,它确实知道标签Foo。

HeadType: 
    - Bar: 0 
    Foo: FooTest 

有没有办法实现这一目标?我曾尝试下面这也多年平均值的工作:

HeadType: 
    FooType: 
    - Bar: 0 
     Foo: FooTest 

我使用的YAML点网系列化“YamlDotNet.Serialization”,这是序列化是如何工作的:

Deserializer deserializer = new Deserializer(); 
    var result = deserializer.Deserialize<RootType>(yamlInput1); 

其中root是类包含HeadType。

回答

0

尝试使用

HeadType: 
    - !bar 
    Bar: 0 
    - !foo 
    Bar: 0 
    Foo: FooTest 

YamlDotNet不意味着基于本内容的实际类型,所以你需要告诉它这类型,它通过使用标签。加载时,您需要使用解串器注册这些标签:

deserializer.RegisterTagMapping("!bar", typeof(BarType)); 
deserializer.RegisterTagMapping("!foo", typeof(FooType));