How to searialize an interface in C#?
We have an object of class Asset. This Asset has an interface member EntityCollection of type IList<AssetEntity>
. In a .asmx web service, we are serializing this Asset Object into XM开发者_开发知识库L and returning this XML.
But we are getting an error "Cannot serialize member EntityCollection of type System.Collections.Generic.IList[AssetEntity]"
Please help as to how to serialize.
The problem is that the actual object type (that is implementing IList<AssetEntity>
may not be a serializable type. The solution will be to implement IXmlSerializable interface in Asset class and provide your own implementation for serializing to/from XML. As EntityCollection is a list of AssetEntity, serializing it as array of xml elements(nodes) should do the trick.
Here's a webcast about controlling xml serialization: http://www.microsoft.com/uk/msdn/nuggets/nugget/96/Using-custom-serialization-with-ASMX-V20-Web-Services.aspx
This is another useful link in case you run into the trouble: forum where you may find answers related to xml serialization in asmx: http://social.msdn.microsoft.com/Forums/en-US/asmxandxml/threads/
XML serialization has some very picky rules about how collection-typed properties must be declared in order to serialize. Notably, IList<T>
fails because it does not extend the non-generic ICollection
.
You may be able to get around this by exposing two properties: one public get-only ICollection
for XML serialization to consume that is decorated with [XmlElement]
and/or [XmlArrayItem]
specifying the concrete element type(s) to expect within the collection, and one typed as you wish and decorated with [XmlIgnore]
.
You can only de/serialize concrete types. These are the only types of instances that can exist in a program.
Try use plain array instead of ILIst, or just List.
精彩评论