1

I just started working with Yaml and would really appreciate some input. I am creating a YAML and trying to deserailize it to existing C# class. Existing C# class:

    [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;
               }
            }

Now I have a Yaml,

HeadType:
  - Bar: 0
  - Bar: 29

When I try to deserialze the above Yaml,I don't get any error.

But when I change my Yaml to something like below, it doensot know about the tag Foo.

HeadType:
  - Bar: 0 
    Foo: FooTest

Is there a way I can achieve this? I have tried the below which also doesnot work:

HeadType:
  FooType:
    - Bar: 0
      Foo: FooTest

I am using Yaml dot net serialization "YamlDotNet.Serialization" and this is how the serialization is working:

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

where Root is the class containing the HeadType.

anon
  • 367
  • 1
  • 4
  • 18

1 Answers1

0

Try using

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

YamlDotNet does not infer the actual type based on the content present, so you need to tell it which type it is by using tags. When loading, you need to register these tags with the deserializer:

deserializer.RegisterTagMapping("!bar", typeof(BarType));
deserializer.RegisterTagMapping("!foo", typeof(FooType));
flyx
  • 35,506
  • 7
  • 89
  • 126