XmlSerializer - There was an error reflecting type
Remember that serialized classes must have default (i.e. parameterless) constructors. If you have no constructor at all, that's fine; but if you have a constructor with a parameter, you'll need to add the default one too.
Look at the inner exception that you are getting. It will tell you which field/property it is having trouble serializing.
You can exclude fields/properties from xml serialization by decorating them with the [XmlIgnore]
attribute.
XmlSerializer
does not use the [Serializable]
attribute, so I doubt that is the problem.
Most common reasons by me:
- the object being serialized has no parameterless constructor
- the object contains Dictionary
- the object has some public Interface members
I had a similar problem, and it turned out that the serializer could not distinguish between 2 classes I had with the same name (one was a subclass of the other). The inner exception looked like this:
'Types BaseNamespace.Class1' and 'BaseNamespace.SubNamespace.Class1' both use the XML type name, 'Class1', from namespace ''. Use XML attributes to specify a unique XML name and/or namespace for the type.
Where BaseNamespace.SubNamespace.Class1 is a subclass of BaseNamespace.Class1.
What I needed to do was add an attribute to one of the classes (I added to the base class):
[XmlType("BaseNamespace.Class1")]
Note: If you have more layers of classes you need to add an attribute to them as well.