I have an some XML that I wish to serialize and deserialize using the XmlSerializer. I wish to be able to possibly use other serial formats in the future, such as JSON, YAML, etc, so my resulting classes from deserialization should share the same interface.
However, my interface contains an array of objects that also use an interface:
public interface IConfiguration
{
ICommand[] Commands { get; set; }
}
public Interface ICommand
{
// Command properties
}
[System.SerializableAttribute()]
public XmlConfiguration : IConfiguration
{
ICommand[] Commands { get; set; }
}
[System.SerializableAttribute()]
public XmlCommand : ICommand
{
// Command properties
}
How will the XML deserialize operation know to use the XmlCommand concrete type when creating the XmlConfiguration object?
Thinking as I type...
I guess I could add a constructor to the XmlConfiguration class to assign an empty array of the concrete type, but I am not sure if this would work as intended?
[System.SerializableAttribute()]
class XmlConfiguration : IConfiguration
{
public XmlConfiguration()
{
Commands = new XmlCommand[] { };
}
}
Update: I realize there is the XmlArrayItemAttribute attribute available, unsure if it will work for interfaces though:
class XmlConfiguration : IConfiguration
{
[System.Xml.Serialization.XmlArrayItemAttribute(typeof(XmlCommand))]
public ICommand[] Commands { get; set; }
}
Update: I can probably also do:
class XmlConfiguration : IConfiguration
{
[System.Xml.Serialization.XmlIgnoreAttribute()]
public ICommand[] Command
{
get => CommandsConcrete;
set => CommandsConcrete = (XmlCommand[])value;
}
[System.Xml.Serialization.XmlElementAttribute(ElementName = "Commands")]
public XmlCommand[] CommandsConcrete { get; set; }
}
[XmlInclude]to list all inherited types. Can you switch to base class or use another serializer? I am quite sure json.net will manage it withTypeNameHandling.Auto.XmlIncludeAttributebut the example code on the MSDN page is blank... so I had little to go on how to properly apply it :(