Click here to Skip to main content
Click here to Skip to main content

Serializing to a String

, 11 Jul 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
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 not marked to not 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 xmlnsString =
      "xmlns:xsi=\"http://www.w3.org/2001/" + 
      "XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"";
 
    private const string headerString = "";
 
    /// <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);
          var str =  stringWriter.ToString();
          return str.Replace(xmlnsString, "{1}").Replace(headerString, "{0}")
              .Replace("\r\n", string.Empty);
        }
      }
      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 an 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)

Share

About the Author

Clifford Nelson
Software Developer (Senior) ETeam/Delloitte
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 three years has been working primarily as a senior WPF/C# and Silverlight/C# developer. Currently working as WPF developer with NBC Universal in Universal City, CA

Comments and Discussions

 
GeneralMy vote of 1 PinprofessionalH. Mueller26-Jul-13 1:28 
GeneralRe: My vote of 1 PinmemberClifford Nelson26-Jul-13 5:39 
GeneralMessage Removed PinmemberArash M. Dehghani27-Jul-13 0:54 
GeneralRe: My vote of 1 Pinmemberthe.Kris29-Jul-13 7:24 
GeneralMessage Removed PinmemberArash M. Dehghani12-Jul-13 1:26 
Message Removed

modified 27-Jan-15 14:43pm.

AnswerMessage Removed PinmemberClifford Nelson12-Jul-13 5:56 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150301.1 | Last Updated 11 Jul 2013
Article Copyright 2013 by Clifford Nelson
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid