简体   繁体   中英

trying to serialize and deserialize entity object in c#

I am using two methods below to serialize/deserialize entity framework object (ver. 4.0). I tried several ways to accomplish this, and had no luck. Serialization works fine. I get nice xml formatted string, but when I try to deserialize I get error in XML. How is that possible?

Thanks.

    public static string SerializeObject(Object obj)
    {
        XmlSerializer ser = new XmlSerializer(obj.GetType());
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        System.IO.StringWriter writer = new System.IO.StringWriter(sb);
        ser.Serialize(writer, obj);
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(sb.ToString());
        string xml = doc.InnerXml;
        return xml;
    }
    public static object DeSerializeAnObject(string xml, Type objType)
    {
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xml);
        XmlNodeReader reader = new XmlNodeReader(doc.DocumentElement);
        XmlSerializer ser = new XmlSerializer(objType);
        object obj = ser.Deserialize(reader);
        return obj;
    }

I use generic methods to serialize and deserialize:

/// <summary>
/// Serializes an object to Xml as a string.
/// </summary>
/// <typeparam name="T">Datatype T.</typeparam>
/// <param name="ToSerialize">Object of type T to be serialized.</param>
/// <returns>Xml string of serialized type T object.</returns>
public static string SerializeToXmlString<T>(T ToSerialize)
{
    string xmlstream = String.Empty;

    using (MemoryStream memstream = new MemoryStream())
    {
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
        XmlTextWriter xmlWriter = new XmlTextWriter(memstream, Encoding.UTF8);

        xmlSerializer.Serialize(xmlWriter, ToSerialize);
        xmlstream = UTF8ByteArrayToString(((MemoryStream)xmlWriter.BaseStream).ToArray());
    }

    return xmlstream;
}

/// <summary>
/// Deserializes Xml string of type T.
/// </summary>
/// <typeparam name="T">Datatype T.</typeparam>
/// <param name="XmlString">Input Xml string from which to read.</param>
/// <returns>Returns rehydrated object of type T.</returns>
public static T DeserializeXmlString<T>(string XmlString)
{
    T tempObject = default(T);

    using (MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(XmlString)))
    {
        XmlSerializer xs = new XmlSerializer(typeof(T));
        XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);

        tempObject = (T)xs.Deserialize(memoryStream);
    }

    return tempObject;
} 

// Convert Array to String
public static String UTF8ByteArrayToString(Byte[] ArrBytes)
{ return new UTF8Encoding().GetString(ArrBytes); }
// Convert String to Array
public static Byte[] StringToUTF8ByteArray(String XmlString)
{ return new UTF8Encoding().GetBytes(XmlString); }

i THINK the issue is with this line:

string xml = doc.InnerXml;

you want ALL the xml, not just the xml inside the root node.

Just return sb.ToString() , loading into the XmlDocument is not doing anything.

Some redundancies and usings was excluded. Refactored and cleaned up:

namespace MyProject
{
    using System.IO;
    using System.Text;
    using System.Xml;
    using System.Xml.Serialization;

    public static class Serializer
    {
        #region Public Methods and Operators

        /// <summary>
        ///     Deserializes Xml string of type T.
        /// </summary>
        /// <typeparam name="T">Datatype T.</typeparam>
        /// <param name="XmlString">Input Xml string from which to read.</param>
        /// <returns>Returns rehydrated object of type T.</returns>
        public static T DeserializeXmlString<T>(string xmlString)
        {
            T tempObject;

            using (var memoryStream = new MemoryStream(StringToUTF8ByteArray(xmlString)))
            {
                var xs = new XmlSerializer(typeof(T));
                tempObject = (T)xs.Deserialize(memoryStream);
            }

            return tempObject;
        }

        /// <summary>
        ///     Serializes an object to Xml as a string.
        /// </summary>
        /// <typeparam name="T">Datatype T.</typeparam>
        /// <param name="toSerialize">Object of type T to be serialized.</param>
        /// <returns>Xml string of serialized type T object.</returns>
        public static string SerializeToXmlString<T>(T toSerialize)
        {
            string xmlstream;

            using (var memstream = new MemoryStream())
            {
                var xmlSerializer = new XmlSerializer(typeof(T));
                var xmlWriter = new XmlTextWriter(memstream, Encoding.UTF8);

                xmlSerializer.Serialize(xmlWriter, toSerialize);
                xmlstream = UTF8ByteArrayToString(((MemoryStream)xmlWriter.BaseStream).ToArray());
            }

            return xmlstream;
        }

        #endregion

        #region Methods

        private static byte[] StringToUTF8ByteArray(string xmlString)
        {
            return new UTF8Encoding().GetBytes(xmlString);
        }

        private static string UTF8ByteArrayToString(byte[] arrBytes)
        {
            return new UTF8Encoding().GetString(arrBytes);
        }

        #endregion
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM