How to Serialize and DeSerialize an ArrayList having a custom object inside it

Poster
Posted by in C# category on for Intermediate level | Views : 69380 red flag

This article describes how to Serialize and DeSerialize an ArrayList having a custom object inside it.
Introduction
While working with a complex project, I got a requirement where I had to put my business objects into an ArrayList, serialize it and store the serialized xml string into database so that later on I can retrieve the xml string from database DeSerialize it and bind to any Data controls like GridView or Repeater control.


Adding records into ArrayList

To describe how to do that, lets first add the business object into an ArrayList. To do that declare an ArrayList, initialize the business object, set its properties and add it into the ArrayList. Below is the sample code.

ArrayList aList = new ArrayList();

MyBusinessObject obj = new MyBusinessObject();

obj.Name = "MyName";

obj.Address = "MyAddress";

obj.Phone = 435345;

aList.Add(obj);

Same way, you can add multiple objects into the ArrayList.

Serializing the ArrayList

Lets see how to Serialize this ArrayList. Below function is to Serialize the ArrayList. This function will take ArrayList as the parameter and return serialized Xml string. You can simply copy-paste the function and use it.

/// <summary>

/// Serialize the ArrayList

/// </summary>

/// <param name="obj"></param>

/// <returns></returns>

private string SerializeArrayList(ArrayList obj)

{

System.Xml.XmlDocument doc = new XmlDocument();

Type[] extraTypes = new Type[1];

extraTypes[0] = typeof(MyBusinessObject);

System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(ArrayList), extraTypes);

System.IO.MemoryStream stream = new System.IO.MemoryStream();

try

{

serializer.Serialize(stream, obj);

stream.Position = 0;

doc.Load(stream);

return doc.InnerXml;

}

catch { throw; }

finally

{

stream.Close();

stream.Dispose();

}

}




In the above function, I am:

  1. Instantiating the XmlDocument object, this will help me in loading the stream into XmlDocument object.
  2. Defining array of Type and storing the type of MyBusinessObject into its first element. This will be used as the parameter of the XmlSerializer object.
  3. Instantiating XmlSerializer object by passing type of ArrayList and an array of my business object type. This will help me in calling actual Serialize function of the XmlSerializer object.
  4. Instantiating MemoryStream, this will be passed to the Serialize method of the XmlSerializer object.
  5. Inside the Try block, I am calling Serialize object by passing Stream and object to serialize (in this case ArrayList).
  6. Setting the current postion within the stream so that Load method of XmlDocument object loads the whole stream from the begining.
  7. Calling Load method of the XmlDocument object and passing stream as the parameter.
  8. Returning the InnerXml of the XmlDocument object, this will be the actual serialized xml string.
  9. In the catch block I am simply throwing the exeption, if any.
  10. Closing the stream and disposing it.

You can call this function as follows

string serializedData = SerializeArrayList(list);

serializedData variable will have the serialized xml string, you can store it into the database.

DeSerializing ArrayList (Serialized xml string of ArrayList)

DeSerializing the serialized ArrayList is a bit simple. Following function takes serializedData (string) as parameter and return the ArrayList after DeSerializing. You can copy-paste the function and use it.

/// <summary>

/// DeSerialize serialized string

/// </summary>

/// <param name="serializedData"></param>

/// <returns></returns>

private ArrayList DeSerializeArrayList(string serializedData)

{

ArrayList list = new ArrayList();

Type[] extraTypes = new Type[1];

extraTypes[0] = typeof(MyBusinessObject);

System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(ArrayList), extraTypes);

XmlReader xReader = XmlReader.Create(new StringReader(serializedData));

try

{

object obj = serializer.Deserialize(xReader);

list = (ArrayList)obj;

}

catch

{

throw;

}

finally

{

xReader.Close();

}

return list;

}

In the above function, I am.

  1. Declaring an ArrayList variable.
  2. Defining a array of Type variable and storing the type of  my business object into its first element.
  3. Instantiating XmlSerializer object and passing type of arraylist and array of Type as parameter, (the way I have done in case of Serializing ArrayList)
  4. Reading the string of serialized data (string) into StringReader and storing it into XmlReader.
  5. Inside try block, passing the XmlReader into the DeSerialze method of the XmlSerializer class. DeSerialize method will return an object.
  6. UnBoxing the object into an ArrayList and storing into my ArrayList variable, I had declared in the 1st point.
  7. Throwing the error, if any
  8. Closing the XmlReader object
  9. Returing the ArrayList.

You can call this method as follows

ArrayList list = DeSerializerrayList(serializedData);

 

// Bind the data to GridView

 

GridView1.DataSource = list;

GridView1.DataBind();


Hope this article will be useful for the visitors. Thanks and take care.

NOTE: This article was originally written by Sheo Narayan

Edited: Visitors may read http://stackoverflow.com/questions/1327064/serialization-of-an-abstract-class post as suggested by Xr280xr to further enhance this solution.

Page copy protected against web site content infringement by Copyscape

About the Author

Poster
Full Name: Ms poster
Member Level:
Member Status: Member
Member Since: 8/29/2007 10:18:25 AM
Country:


-- Hobby for DotNet

Login to vote for this post.

Comments or Responses

Posted by: Xr280xr on: 12/15/2009
Nice article except I recently read that using the extra types overload of a constructor can have some serious overhead. He put it:

"Additionally, with XmlSerializer if you go the custom ctor route, it is important to cache and re-use the XmlSerializer instance; otherwise a new dynamic assembly is loaded per usage - very expensive (they can't be unloaded). If you use the simple constructor it caches and re-uses the model, so only a single model is used."

The entire posting can be found here: http://stackoverflow.com/questions/1327064/serialization-of-an-abstract-class

If this is true, I would recommend updating this article to mention it.

Login to post response

Comment using Facebook(Author doesn't get notification)