Emu
Emu

Reputation: 87

Serialize property of type object

I have a serializable class which contains some properties, including a variable of type object. I want my class to be able to contain different (of course serializable) objects. The problem is, that I get an exception during serialization:

Use the XmlInclude or SoapInclude attribute to specify types that are not known statically

I created a small sample for this issue:

class Program
{
    static void Main(string[] args)
    {
        SerializeableTestClass testClass = new SerializeableTestClass();

        testClass.Params = new ExtendedParams();

        MemoryStream ms = new MemoryStream();
        XmlSerializer xmlf = new XmlSerializer(testClass.GetType());
        xmlf.Serialize(ms, testClass);
        ms.Capacity = (int)ms.Length;
        ms.Close();
        byte[] array =  ms.GetBuffer();
    }
}

[Serializable]
public class SerializeableTestClass
{
    [XmlElement(ElementName = "Params")]
    public object Params;
}

[Serializable]
public class ParamsBase
{
    [XmlElement(ElementName = "SomeValue")]
    public Int32 SomeValue;
}

[Serializable]
public class ExtendedParams : ParamsBase
{
    [XmlElement(ElementName = "SomeNewValue")]
    public Int32 SomeNewValue;
}

Is there a possibility to serialize and deserialize this class without specifying the concrete type of "Params" ???

Best regards

Upvotes: 2

Views: 2458

Answers (3)

Me.Name
Me.Name

Reputation: 12544

Is it acceptable to include all the possible types on the class that is serialized? (That is what the message means, that no type info is included for ExtendedParams).

You can include it in the XmlSerializeritself, or include it on the main class:

[Serializable]
[XmlInclude(typeof(ParamsBase))]
[XmlInclude(typeof(ExtendedParams))]
public class SerializeableTestClass
{
    [XmlElement(ElementName = "Params")]    
    public object Params;
}

But to dynamically serialize if you don't know all the types:

//static: XmlSerializer xmlf = new XmlSerializer(testClass.GetType(),new Type[]{typeof(ExtendedParams)});

//dynamic:
Type[] extratypes = testClass.Params == null ? null : new Type[] { testClass.Params.GetType() };
XmlSerializer xmlf = new XmlSerializer(testClass.GetType(), extratypes );

Upvotes: 2

Fung
Fung

Reputation: 3558

As the exception message suggests, you need to specify the derived type so that it can be recognized:

[Serializable]
[XmlInclude(typeof(ExtendedParams))]
public class SerializeableTestClass
{
    [XmlElement(ElementName = "Params")]
    public object Params;
}

Upvotes: 0

Mohammad Gabr
Mohammad Gabr

Reputation: 221

modify your code , when you initialize the XmlSerializer

 XmlSerializer xmlf = new XmlSerializer(testClass.GetType(),new Type [] {typeof(ExtendedParams)});

this will let the XmlSerializer know about the other types in the class

Upvotes: 1

Related Questions