terça-feira, 21 de julho de 2015

Serializer

public class Serializer
    {
        public static Object Deserialize(String xml, Type type)
        {
            try
            {
                System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(type);
                using (System.IO.MemoryStream stream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(xml), false))
                {
                    var file = (object)serializer.Deserialize(stream);
                    return file;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static String Serialize(Object serializable, Type type)
        {
            if (serializable == null)
            {
                throw new ArgumentNullException("serializable");
            }

            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(type);
            try
            {
                using (System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(stream, System.Text.Encoding.UTF8))
                {
                    serializer.Serialize(writer, serializable);
                    stream = (System.IO.MemoryStream)writer.BaseStream;
                    return System.Text.Encoding.UTF8.GetString(stream.ToArray());
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                stream.Close();
            }
        }

    }
Postar um comentário