简体   繁体   中英

Do I really need to write this “SerializationHelper”?

I just wrote this SerializationHelper class, but I can't believe this is necessary!

using System.IO;
using System.Xml.Serialization;

public static class SerializationHelper
{
    public static string Serialize<T>(T obj)
    {
        var outStream = new StringWriter();
        var ser = new XmlSerializer(typeof(T));
        ser.Serialize(outStream, obj);
        return outStream.ToString();
    }

    public static T Deserialize<T>(string serialized)
    {
        var inStream = new StringReader(serialized);
        var ser = new XmlSerializer(typeof(T));
        return (T)ser.Deserialize(inStream);
    }
}

And it's used like this:

var serialized = SerializationHelper.Serialize(myObj);

and:

var myObj = SerializationHelper.Deserialize<MyType>(serialized)

Am I missing something in the .NET framework? This is not rocket science!

In actual fact, the bits where you call the .NET API are these:

var ser = new XmlSerializer(typeof(T));
ser.Serialize(outStream, obj);

var ser = new XmlSerializer(typeof(T));
var obj = (T) ser.Deserialize(inStream);

The rest of the code is your personal specialisation. I don't think that two lines of code is too much for calling an API. You could always condense them, eg

(new XmlSerializer(typeof(T))).Serialize(outStream, obj);

var obj = (T) (new XmlSerializer(typeof(T))).Deserialize(inStream);

Purely as an aside, I should point out that I regard storing XML data in string variables as a Code Smell. As soon as you take XML data out of its raw binary form ( XDocument , XmlDocument , XPathDocument or any other type of DOM), you run up against encoding issues. What if a developer serialises an object to a string with encoding X, then writes the string to a disk file with encoding Y? Not very safe. Besides which, if encoding X is not UTF-16, how would you even represent the data in a .NET string?

It's useful if you are doing any real amount (>1) of serialization/deserialization within a project. This was the case for me one time, so I just put a similar class in a Utils library, along with other reusable functions.

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