sexta-feira, 17 de julho de 2015

Serializer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;

namespace Lapuinka.Helper.Serializer
{
    public enum SerializerType
    {
        SOAP = 1,
        JSON = 2
    }

    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, SerializerType typeSerializer)
        {
            if (serializable == null)
            {
                throw new ArgumentNullException("serializable");
            }
            if (typeSerializer == SerializerType.SOAP)
            {
                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();
                }
            }
            else
            {
                JavaScriptSerializer ser = new JavaScriptSerializer();
                return ser.Serialize(serializable);
            }
        }
    }
}


Postar um comentário