Click here to Skip to main content
15,867,308 members
Articles / Programming Languages / C#
Tip/Trick

Helper for Serializing to a String

Rate me:
Please Sign up or sign in to vote.
3.86/5 (8 votes)
11 Jul 2013CPOL2 min read 18K   111   12   9
Helper for serializing objects to a string

Introduction

I had a need to save a copy of a local variable to a class, but the Settings does not seem to support objects that are of a Type that is defined in the local project, so I could have created a special serializer, but decided that I wanted to create something that was more generic, and since wanted to save it in the Settings file, converting it to a string seemed like the best solution, and using XML would be a preferred format since it is easy to understand what is being saved. The next problem was that the XmlSerializer needs a Stream for conversion. With the complexity associate with handling the Stream, it seemed best to encapsulate the functionality using generics. Since there is no state required, it is preferable to implement these methods as static.

Potential Serializer Gotchas

There are a number of issues that you can run into when serializing, and the compiler does not seem to be much help and the error messages are not much either:

  • Classes serialized must be public
  • All properties that are marked to be serialized must have both a setter and getter.

The Code

The class that does the serialization and deserialization is two short static methods in a static class:

public static class Serializer
{
        private const string xmlnsString1 = "xmlns:xsi=\"<a href="http://www.w3.org/2001/XMLSchema-instance\">http://www.w3.org/2001/XMLSchema-instance\</a>"" ;
        private const string xmlnsString2 = "xmlns:xsd=\"<a href="http://www.w3.org/2001/XMLSchema\">http://www.w3.org/2001/XMLSchema\</a>"";

        /// <summary>
        /// Serialize an object to a string.
        /// </summary>
        public static string SerializedToString<T>(T serializableObject)
        {
            if (serializableObject.Equals(default(T))) return string.Empty;
            try
            {
                var serializer = new XmlSerializer(typeof(T));
                using (var stringWriter = new StringWriter())
                {
                    serializer.Serialize(stringWriter, serializableObject, 
				new XmlSerializerNamespaces());
                    var str = stringWriter.ToString().Replace(xmlnsString1, 
				string.Empty).Replace(xmlnsString2, string.Empty);
                    return str;
                }
            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }
    }

    /// <summary>
    /// Deserialize an string into an object
    /// </summary>
    public static T DeSerializeFromString<t>(string serializedObject)
    {
      if (string.IsNullOrWhiteSpace(serializedObject)) return default(T);
      try
      {

        var stringReader = new StringReader(string.Format(serializedObject,
              headerString, xmlnsString));
        var serializer = new XmlSerializer(typeof(T));
        return (T)serializer.Deserialize(stringReader);
      }
      catch (Exception exception)
      {
        return default(T);
      }
   }
}

There is really no error handling, but it may be desirable to put it in. Also, the code removes some text that is extremely repetitive: the XML declaration line, and the declaration of the namespaces. The code is done so that if something besides what the code expects, there will be no harm, but some may think that the saved space is not worth it.

Summary

These methods makes it very easy to serialize an object to and from a string, but is not really appropriate for saving the serialization since it would the XMLSerializer supports a type of Stream, and can use a Stream to more directly support saving to file. There is also disadvantages of possible changes in the object that will not be supported unless there is some customization done on the objects for serialization, and XML is not an efficient way to save data.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Clifford Nelson Consulting
United States United States
Has been working as a C# developer on contract for the last several years, including 3 years at Microsoft. Previously worked with Visual Basic and Microsoft Access VBA, and have developed code for Word, Excel and Outlook. Started working with WPF in 2007 when part of the Microsoft WPF team. For the last eight years has been working primarily as a senior WPF/C# and Silverlight/C# developer. Currently working as WPF developer with BioNano Genomics in San Diego, CA redesigning their UI for their camera system. he can be reached at qck1@hotmail.com.

Comments and Discussions

 
GeneralMy vote of 1 Pin
nobodyxxxxx26-Jul-13 0:28
nobodyxxxxx26-Jul-13 0:28 
GeneralRe: My vote of 1 Pin
Clifford Nelson26-Jul-13 4:39
Clifford Nelson26-Jul-13 4:39 
GeneralRe: My vote of 1 Pin
the Kris29-Jul-13 6:24
the Kris29-Jul-13 6:24 
GeneralRe: My vote of 1 Pin
Tencor Developer8-Jun-18 5:36
Tencor Developer8-Jun-18 5:36 
AnswerRe: My vote of 1 Pin
Clifford Nelson8-Jun-18 7:29
Clifford Nelson8-Jun-18 7:29 
So I looked into your statement about being able to remove the namespaces and found XmlSerializerNamespaces but using this still gives you the defaults, so unless you have something else your criticism is pure BS. And you are an ass to boot being that you put me down like that.
GeneralRe: My vote of 1 Pin
the Kris9-Jun-18 7:18
the Kris9-Jun-18 7:18 
AnswerRe: My vote of 1 Pin
Clifford Nelson11-Jun-18 6:45
Clifford Nelson11-Jun-18 6:45 
GeneralRe: My vote of 1 Pin
Tencor Developer8-Jun-18 5:28
Tencor Developer8-Jun-18 5:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.