terça-feira, 20 de outubro de 2009

Classe genérica para serialização / deserialização em C#



Encontrei nas pesquisas pelo Google uma classe genérica para serialização/deserialização muito boa... segue o código:


public class SerializationUtil
{
/// <summary>
/// Deserializes the specified XML.
/// </summary>
/// <typeparam name="T">Type</typeparam>
/// <param name="xml">The XML.</param>
/// <returns></returns>
public static T Deserialize<T>(string xml)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(new XmlTextReader(xml, XmlNodeType.Element, null));
}

public static List<T> DeserializeList<T>(string xml, string nodeName)
{
List<T> lst = new List<T>();
XmlDocument doc = new XmlDocument();
doc.InnerXml = xml;
XmlNodeList nodeList = doc.SelectNodes(nodeName);
if (nodeList != null)
{
foreach (XmlNode node in nodeList)
{
lst.Add(Deserialize<T>(node.OuterXml));
}
}
return lst;
}

/// <summary>
/// Serializes the specified obj to xml.
/// </summary>
/// <param name="obj">The obj.</param>
/// <returns></returns>
public static string Serialize(object obj)
{
string returnXml = string.Empty;
XmlSerializer serializer = new XmlSerializer(obj.GetType(), GetObjectTypes(obj).ToArray());
using (StringWriter writer = new StringWriter(CultureInfo.CurrentCulture))
{
serializer.Serialize(new XmlTextWriter(writer), obj);
returnXml = writer.ToString();
}
return returnXml;
}

private static List<Type> GetObjectTypes(object input)
{
List<Type> types = new List<Type>();
Assembly currentAssembly = input.GetType().Assembly;
Type currentType = input.GetType();
//Query our types. We could also load any other assemblies and
//query them for any types that inherit from the currentType
foreach (Type tempType in currentAssembly.GetTypes())
{
if (!tempType.IsAbstract && !tempType.IsInterface && currentType.IsAssignableFrom(tempType))
{
types.Add(tempType);
}
}
return types;
}
}




Exemplo para usar:


List<User> lstUsr = UserSerializationUtil.DeserializeList<ContentProvider>(StringComXml, "users/user");



Exemplo para Serializar um obejto para XML:


List<User> lst = helper.GetUsers();
Response.Write(SerializationUtil.Serialize(lst));

2 comentários:

Anônimo disse...

Ramiro, muito boa essa classe de serialização. Estou utilizando em meu sistema.

Abraços.


Alessandro Gonzalez
Campo Grande-MS

Anônimo disse...

tem uma bem interessante neste link também:
http://nerdice.net/#/articles/criando-uma-classe-generica-para-serializacao-deserializacao-xml

Postar um comentário