views:

53

answers:

2

I want to serialize objects to text, but I want to preserve the type info so that I may deserialize without a reference to the type object.

XML Serialization gives me the text I want, but does not keep the type info. What I've read about binary serialization is that it keeps the type info, but its not readable. Looks like the SoapFormater may do what I want, but I'm not sure if this is appropriate.

My goal is to stick the serialized string into a string object, which eventual gets stored in a column in the database (this outside of my control at the moment).

For example, I have a base class:

public class PluginSettings
{
    private string name;
    public string Name { ... }
}

and each plugin can derive from this to save its own settings.

public class ACBPluginSettings : PluginSettings
{
    private string mySetting;
    ...
}

Possible solution I came up with: Use BinaryFormatter, then convert to Base64 string. This gets the job done but its not human readable.

A: 

Even the BinaryFormatter returns an object (or object graph actually) which you would still need to cast to the appropriate type. From the MSDN example:

BinaryFormatter formatter = new BinaryFormatter();
Hashtable addresses = (Hashtable) formatter.Deserialize(fs);

I assume you would like to do something like:

CustomObject obj = new CustomObject();
formatter.Serialize(fs, obj);
var deserializedObj = formatter.Deserialize(source);

And have deserializedObj typed as a CustomObject. Unfortunately I don't believe that's possible (or at least I can't think of any way to accomplish it).

Chris Pebble
Yes this is what I want to do, but I know the base class. I want to deal with the base type only without knowing about the derived types.
TheSean
I ended up using BinaryFormatter, because I never figured out a way to serialize to text with type info.
TheSean
A: 

I think that System.Runtime.Serialization.NetDataContractSerializer can do what you're looking for.

From MSDN:

The NetDataContractSerializer differs from the DataContractSerializer in one important way: the NetDataContractSerializer includes CLR type information in the serialized XML, whereas the DataContractSerializer does not. Therefore, the NetDataContractSerializer can be used only if both the serializing and deserializing ends share the same CLR types.

Jay