XML deserialization - cannot have child contents to be deserialized as an object

Element MyValue from namespace http://schemas.datacontract.org/2004/07/Services cannot have child contents to be deserialized as an object. Please use XmlNode[] to deserialize this pattern of XML.

 

I was playing with DataContractSerializer, and getting this strange error when performing de-serialization (turning XML back into an object of type MyClass).

[DataContract]
public class MyClass
{
    [DataMember]
    public string MyName;

    [DataMember]
    public object MyValue;
}

 

The error message actually is pretty clear about what the issue is, but English is a sucky language.  Let me highlight what the error message is really saying:

Element MyValue from namespace http://schemas.datacontract.org/2004/07/Services cannot have child contents to be deserialized as an object. Please use XmlNode[] to deserialize this pattern of XML.

Read it again:

Element MyValue cannot be deserialized as an object.

 

The deserializer was actually talking about the fact that it can't turn <MyValue>1</MyValue> back into an object of the type Object.

If you change your DataContract to

[DataContract]
public class MyClass
{
    [DataMember]
    public string MyName;

    [DataMember]
    public string MyValue;
}

 

Then the deserializer will be happy.