Monday, April 25, 2011

How to Serialize and DeSerialize a Generic List

private void button1_Click(object sender, EventArgs e)
{
List<Employee> emps = new List<Employee>();
emps.Add(new Employee("1", "Sabu"));
emps.Add(new Employee("2", "John"));
emps.Add(new Employee("3", "Tom"));
emps.Add(new Employee("4", "George"));
string serializedXmlString = XmlSerialize(emps);
List<Employee> deserializedEmps = XmlDeserialize(serializedXmlString);
}

//XmlSerialize method
public string XmlSerialize(List<Employee> emps)
{
System.Xml.Serialization.XmlSerializer xmlSer = new System.Xml.Serialization.XmlSerializer(emps.GetType());
StringWriter textWriter = new StringWriter();
xmlSer.Serialize(textWriter, emps);
xmlSer = null;
return textWriter.ToString();
}


//XmlDeserialize method
public List<Employee> XmlDeserialize(String data)
{
System.Xml.Serialization.XmlSerializer xmlSer = new System.Xml.Serialization.XmlSerializer(typeof(List<Employee>));
TextReader reader = new StringReader(data);
object obj = xmlSer.Deserialize(reader);
return (List<Employee>)obj;
}


//Employee Class with Serializable attribute

[Serializable]
public class Employee
{
public Employee()
{
ID = "";
Name = "";
}

public Employee(String id, String name)
{
ID = id;
Name = name;
}


public string ID { get; set; }
public string Name { get; set; }
}

4 comments:

  1. Hi,

    Thnax for yours valuable article.

    for SOA architecture xml serialization and de-serialization is main concern.

    Again thank you.

    ReplyDelete
  2. Thanks, I've looked at so many ways on how to serialize and de-serialize a list and most don't work correctly, your is simple and works great.

    ReplyDelete
  3. thanks for your post.

    i want to deserialize that text in JSON, but i cant

    i am using vb.net
    and the senctence is

    datos1 = TryCast(Newtonsoft.Json.JsonConvert.DeserializeObject(Of datosPrueba)(sLine), datosPrueba)

    in datosPrueba is a clas with all the objets, name, idresource....
    but i cant
    the text in JSON is:


    [{"idReservation":2560,
    "startDate":"30/09/2013 09:00",
    "endDate":"30/09/2013 09:10",
    "timeOut":"24/09/2013 16:02:23",
    "idResource":1477,
    "resourceDescription":"Profesional",
    "players":
    [{"idPlayer":283,
    "idCustomer":2,
    "name":"Ignacio",
    "image":"/public/images/interface/customer/user.png",
    "total":0}],
    "anulable":true,
    "name":"Ignacio",
    "price":0,
    "status":"Reservada",
    "parententityname":"",
    "idparententity":"",
    "unixTime":1380524400},

    sorry, my english is very bad
    thanks

    ReplyDelete