lunedì 4 febbraio 2013

Serializzazione e deserializzazione in c#

Nell'interscambio di dati è usuale utilizzare formati xml. Se usiamo c# come linguaggio di programmazione, ci sono dei metodi del framework che ci aiutano parecchio. Inoltre dalla versione 3.5 del framework potete usare gli "Exstension Method", ovvero potete dotare qualsiasi classe di metodi aggiuntivi, in relazione al tipo.
Combinando le due cose potete scrivere dei metodi per la serializzazione e deserializzazione di classi e renderli generici. Ad esempio:

Con i seguenti "Extension Method"


        /// <summary>
        /// Serializes to XML.
        /// </summary>
        /// <param name="value">The object to serialize.</param>
        /// <returns>
        /// a XElement rappresenting the class serialization
        /// </returns>
        public static XElement SerializeToXML(this object value)
        {
            XmlSerializer x = new XmlSerializer(value.GetType());
            XDocument doc = new XDocument();
            using (XmlWriter xw = doc.CreateWriter())
            {
                x.Serialize(xw, value);
                xw.Close();
            }
            return doc.Root;
        }


        /// <summary>
        /// Deserializes the specified string to an object of type T.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value">The value containing an xml.</param>
        /// <returns>
        /// an object of type T
        /// </returns>
        public static T Deserialize<T>(this string value)
        {
            XElement xElement = XElement.Parse(value);

            return xElement.Deserialize<T>();

        }

        /// <summary>
        /// Deserializes the specified string to an object of type T.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value">The value containing an xml.</param>
        /// <returns>
        /// an object of type T
        /// </returns>
        public static T Deserialize<T>(this XElement value)
        {
            XmlSerializer x = new XmlSerializer(typeof(T));
            T result;
            using (XmlReader xr = value.CreateReader())
            {
                result = (T)x.Deserialize(xr);
                xr.Close();
            }
            return result;
        }







In questo modo, per serializzare una classe dovrete semplicemente scrivere






MyClass a = new MyClass();

XElement xml = a.SerializeToXML();
MyClass b = xml.Deserialize<MyClass>(xml)

Nessun commento:

Posta un commento