Object to String – String to Object

Sometime, you just want to quickly serializes an object to string and deserializes from a string to object. Below are the codes
(If you don’t like the generic version of StringToObject, you can pass the object type as an addition parameter)

public static string ObjectToString(object obj) 
   XmlSerializer serializer = new XmlSerializer(obj.GetType()); 
   string result; 
   using (MemoryStream stream = new MemoryStream()) 
      serializer.Serialize(stream, obj);
      StreamReader reader = new StreamReader(stream); 
      stream.Position = 0;
      result = reader.ReadToEnd();
   return result; 

public static TEntity StringToObject<tentity>(string stringValue) 
   XmlSerializer serializer = new XmlSerializer(typeof(TEntity)); 
   object result; 
   using (StringReader reader = new StringReader(stringValue)) 
      result = serializer.Deserialize(reader);
   return (TEntity)result; 


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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s