I have a curious case of this serialization issue - which has been asked many times on this site and I have gone through a few of these questions and tried the usual items to no avail:
- Add [XmlInclude] to the class throwing the error
- Remove namespaces
- Add a different namespace to each class
To explain further, I have provided a simplified version of my code below. Essentially I am using a WebServiceHost
object to run a RESTful service and one of my endpoints returns an object serialized as XML (I have annotated the object with [DataContract]
and [DataMember]
attributes). This object contains a SerializableDictionary<string, object>
(here) where the value has been typed as object
. I believe this is why it is failing:
- Works fine when the value is assigned a primitive
- When I assign a custom object to the KV pair V, I get the unexpected type exception probably because the Serializer does not know how to serilaize the object / some sort of namespacing issue
Obviously, I am unable to annotate Object.cs with [XmlInclude]
and because it is a service and I am not myself serializing I cannot using something like
new Serializer(typeof(...), new Type[] { ... }}
Any idea's of what I can do? I thought about not typing the dict value as object and rtaher comething more concrete but the problem is that this value can take primitives or cusotm types. Some code to explain the above:
Edit: Updated the code below to make it more clear
[DataContract]
public class ResponseObject
{
[DataMember(Name = "data")]
public SerializableDictionary<string, object> Data { get;set; }
public ResponseObject()
{
Data = new SerializableDictionary<string, object>();
}
}
...
var d1 = new ResponseObject();
d1.Data.Add("some key", "some value"); //WORKS AND SERIALIZES PERFECLTY
var d2 = new ResponseObject();
d2.Data.Add("some other key", new SomeOtherObjecT());
var d3 = new ResponseObject();
d3.Data.Add("another key", d2); //THIS THROWS THE UNEXPECTED TYPE ERROR WHEN SEIRLAIZING SomeOtherObject
Edit: The error is thrown in SerializableDictionary where it is attempting to serialize an object of type ResponseObject. The two are in seperate projects - if that is significant?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…