简体   繁体   中英

How to serialize a collection of key:string, value:object using soapformatter

I need a collection of keys and values (like a dictionary) but it needs to be serializable using the Soapformatter.

Why the soapformatter?
I don't know the type that has to be serialized, I only know the interface that the type implements.

Does anyone have a clue how to crack this nut?

Apparently all it takes is inheriting from Hashtable and adding the following constructors:

[Serializable]
public class StateContainer : Hashtable, IStateContainer
{
    public StateContainer() : base() { }
    public StateContainer(SerializationInfo info, StreamingContext context) : base(info, context) { }
}

Took me half a day to figure this out...

you can then serialize this class like this:

XmlDocument xmlDocument = null;
using (MemoryStream memData = new MemoryStream())
{
    SoapFormatter formatter = new SoapFormatter();
    formatter.Serialize(memData, state);
    memData.Flush();
    memData.Position = 0;
    xmlDocument = new XmlDocument();
    xmlDocument.Load(memData);
}

And deserialize like this:

IStateContainer response = null;
using (MemoryStream memData = new MemoryStream())
{
    using (StreamWriter writer = new StreamWriter(memData))
    {
        writer.Write(state.stateobject);
        writer.Flush();
        memData.Flush();
        SoapFormatter formatter = new SoapFormatter();
        memData.Position = 0;
        response = (IStateContainer)formatter.Deserialize(memData);
    }
}

Hope this can help someone else out there some day :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM