Home > Uncategorized > Cannot serialize member because it implements IDictionary.

Cannot serialize member because it implements IDictionary.

If you ever get an error like Cannot serialize member x of type T, because it implements IDictionary. or something similar whenever you try to return an serialize object with xmlserializer.

Note: This isn’t suitable for webservice use, since the schema is lost.

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Soap;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;

/// <summary>
/// A Web-service friendly version of the  object
/// </summary>
public class XmlSerializable<T> : IXmlSerializable
{
    [NonSerialized]
    public T RawObject;

    public XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(XmlReader reader)
    {
        //deserialization
        var formatter = new SoapFormatter();
        var strXML = reader.ReadInnerXml();
        var msXML = new MemoryStream(Encoding.Default.GetBytes(strXML));
        RawObject = (T)formatter.Deserialize(msXML);
    }

    public void WriteXml(XmlWriter writer)
    {
        //serialization
        var formatter = new SoapFormatter();
        var ms = new MemoryStream();
        formatter.Serialize(ms, RawObject);
        ms.Position = 0;
        var sr = new StreamReader(ms);
        var strXml = sr.ReadToEnd();
        writer.WriteRaw(strXml);
    }
}

Then,  instead of returning T, returns XmlSerializable<T>, and the client accesses the RawObject member of this class to read the return value.

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: