Do I really need to write this "SerializationHelper"?

I just wrote this SerializationHelper class , but I can't believe it 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 is used as follows:

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!

+5
source share
2 answers

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

0
source

In fact, the bits you call the .NET API are as follows:

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

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

- . , API. , .

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

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

, , , XML- . XML- (XDocument, XmlDocument, XPathDocument DOM), . , X, Y? . , X UTF-16, .NET?

+1

All Articles