Buscar contenidos

jueves, 30 de marzo de 2017

Métodos C# [serialize/deserialize] objetos Xml/Json


Concepto de Serialización ( código )


...consiste en un proceso de codificación de un objeto en un medio de almacenamiento (como puede ser un archivo, o un buffer de memoria) con el fin de transmitirlo a través de una conexión en red como una serie de bytes o en un formato humanamente más legible como XML o JSON, entre otros..

----------------------------------



            var indented = Formatting.Indented;

            var settings = new JsonSerializerSettings()
            {
                TypeNameHandling = TypeNameHandling.All
            };

            string serialized = JsonConvert.SerializeObject(obj, indented, settings);

            
            var obj = JsonConvert.DeserializeObject<Model>(serialized, settings);

------

Configuracion para deserializar Interface almacenada en IMemory

        {
            string entry = System.Reflection.MethodBase.GetCurrentMethod().Name;

            string modelJson;
           
            if (_cache.TryGetValue(entry, out modelJson))
            {
                return Newtonsoft.Json.JsonConvert.DeserializeObject<IEnumerable<IAbcET>>(modelJson, new JsonSerializerSettings
                {
                    TypeNameHandling = TypeNameHandling.Auto,
                    NullValueHandling = NullValueHandling.Ignore,
                });               
            }
                              
            var items = this...GetItems().Response;
         
            #region json setting

            var indented = Formatting.Indented;

            var settings = new JsonSerializerSettings()
            {
                TypeNameHandling = TypeNameHandling.All
            };

            string serialized = JsonConvert.SerializeObject(jsonModel, indented, settings);

            #endregion

            _cache.Set(entry, serialized, TimeSpan.FromHours(CacheHourExpire));

            return ConfiguracionPreAnalisisms;
        }

----------------------------------


using Newtonsoft.Json;

using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace ABC.ExtensionsMethods
{


    public static class Serialization
    {

        public static string ToJsonSerialize<T>(this T obj) where T : class
        {
            return JsonConvert.SerializeObject(obj);

            //DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            //using (MemoryStream stream = new MemoryStream())
            //{
            //    serializer.WriteObject(stream, obj);
            //    return Encoding.Default.GetString(stream.ToArray());
            //}
        }

        public static T ToJsonDeserialize<T>(this T obj, string json) where T : class
        {
            return JsonConvert.DeserializeObject<T>(json);

            //using (MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(json)))
            //{
            //    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            //    return serializer.ReadObject(stream) as T;
            //}
        }

        public static string ToXmlSerialize<T>(this T obj)
        {
            try
            {
                string xmlString = null;
                MemoryStream memoryStream = new MemoryStream();
                XmlSerializer xs = new XmlSerializer(typeof(T));
                XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
                xs.Serialize(xmlTextWriter, obj);
                memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
                xmlString = UTF8ByteArrayToString(memoryStream.ToArray()); return xmlString;
            }
            catch
            {
                return string.Empty;
            }
        }

        public static T ToXmlDeserialize<T>(this string xml)
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));

            MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(xml));
            XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
            return (T)xs.Deserialize(memoryStream);
        }

        private static string UTF8ByteArrayToString(byte[] characters)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            string constructedString = encoding.GetString(characters);
            return (constructedString);
        }

        private static Byte[] StringToUTF8ByteArray(string pXmlString)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            byte[] byteArray = encoding.GetBytes(pXmlString);
            return byteArray;
        }


    }


}

No hay comentarios:

Publicar un comentario