mercoledì 12 giugno 2013

Serializing and deserializing classes in C#

When we send data to a different system, is usual to use xml formats. If we use C # as a programming language, there are some framework methods that help us a lot. In the version 3.5 of the framework we can use the "exstension Method" and can equip any class of additional methods, in relation to the type.
Combining the two things you can write methods for serializing and deserializing classes and make them generic.
For example:

With the following "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 this way, you'll just have to serialize a class writing







MyClass a = new MyClass();

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

Nessun commento:

Posta un commento