Monday, February 28

Simple Serialization DeSerialization

there is a need to Serialize an object.
1. sending it to the client so manipulate via javascript
2. persist the object to the database or any other file.

Here's some functions I use on a regular basis
public
staticstring Serialize(object o)
{

if (o==null) { return string.Empty; }

StringWriter writer = new StringWriter();
XmlSerializer xs = new XmlSerializer(o.GetType());
xs.Serialize(writer,o);
writer.Close();
return writer.ToString();


}


public static object DeSerialize(string s, Type t)
{

object ret;
if (s==null) { return null; }
if (s.Length ==0) { return null; }
XmlSerializer xs = new XmlSerializer(t);
ret = xs.Deserialize(new StringReader(s) );
return ret;
}



1 comment:

Cold Chilli said...

Issue with KB886904If you dont have .Net 1.1 SP 1 installed. You may have installed KB886904. This causes the following exception


Unable to generate a temporary class (result=1). error CS1514: { expected error CS1001: Identifier expected error CS1031: Type expected error CS1519: Invalid token '{' in class, struct, or interface member declaration error CS1514: { expected error CS1001: Identifier expected error CS1031: Type expected error CS1519: Invalid token '{' in class, struct, or interface member declaration


to fix this use the following steps
1. using Control Panel uninstall KB886904.
2. Install .Net 1.1 SP 1
3. Install KB886903