【问题标题】:Deserializing Yaml into c# object将 Yaml 反序列化为 c# 对象
【发布时间】:2017-03-04 06:42:14
【问题描述】:

我刚开始使用 Yaml,非常感谢您的意见。我正在创建一个 YAML 并尝试将其脱轨到现有的 C# 类。 现有 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

当我尝试反序列化上述 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 的类。

【问题讨论】:

    标签: c# serialization deserialization yaml yamldotnet


    【解决方案1】:

    尝试使用

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

    YamlDotNet 不会根据存在的内容来推断实际的类型,因此您需要通过标签告诉它是哪种类型。加载时,需要将这些标签注册到反序列化器中:

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

    【讨论】:

      猜你喜欢
      • 2018-01-09
      • 1970-01-01
      • 2020-11-06
      • 1970-01-01
      • 2015-08-05
      • 2014-11-30
      • 2015-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多