aaubry / YamlDotNet

YamlDotNet is a .NET library for YAML
MIT License
2.48k stars 466 forks source link

Serialize/Deserialize an array of different derived types #876

Closed Myonmu closed 7 months ago

Myonmu commented 7 months ago

Hi,

I am fairly new to the library and I am trying to serialize and deserialize a list of types derived from a base type, consider this example:

class BaseType{
    public string name;
}
class TypeA: BaseType{
    public int a;
}
class TypeB: BaseType{
    public string b;
}

And the class I would like to serialize contains a field : public List<BaseType> list.

The desired output is like this:

list:
  - name: "A"
     a: 1
  - name: "B"
     b: "b"

The default serialization actually works and outputs result as desired, but deserialization isn't. The list is empty after default serialization. I would like to know how this could be achieved?

EdwardCooke commented 7 months ago

You probably need a type descriminator to do this.

https://github.com/aaubry/YamlDotNet/wiki/Deserialization---Type-Discriminators#determining-type-based-on-the-value-of-a-key

let me know if you need more assistance. If you do, please post the code for creating your deserializer.

Myonmu commented 7 months ago

You probably need a type descriminator to do this.

https://github.com/aaubry/YamlDotNet/wiki/Deserialization---Type-Discriminators#determining-type-based-on-the-value-of-a-key

let me know if you need more assistance. If you do, please post the code for creating your deserializer.

That worked! Thanks!

EdwardCooke commented 7 months ago

Great! I’ll close this issue then.