Custom serialization with DataContractSerializer

戏子无情 提交于 2019-11-29 06:27:58

The DataContractAttribute and the SerializableAttribute can both be used together. The bonus here is, you don't need to use seperate serialisers either. The DataContractSerialzer is an XmlObjectSerializer, which itself supports [Serializable]. For instance:

[Serializable]
public class TestClass
{
    public string Name { get; set; }
}

{
    var formatter = new DataContractSerializer(typeof(TestClass));
    using (var stream = new MemoryStream())
    {
        var instance = new TestClass { Name = "Matt" };
        formatter.WriteObject(stream, instance);

        stream.Seek(0, SeekOrigin.Begin);

        var second = (TestClass) formatter.ReadObject(stream);
        Console.WriteLine(second.Name);
    }
}

OUTPUT: "Matt"

Using a just a SerializableAttribute attribute we can successfully serialise and deserialise an object using the DataContractSerializer...

Using ISerializable, we can do the same thing:

[Serializable]
public class TestClass2 : ISerializable
{
    public TestClass2() { }
    protected TestClass2(SerializationInfo info, StreamingContext context)
    {
        Name = info.GetString("name").ToUpper();
    }

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("name", Name);
    }

    public string Name { get; set; }
}

{
    var formatter = new DataContractSerializer(typeof(TestClass2));
    using (var stream = new MemoryStream())
    {
        var instance = new TestClass2 { Name = "Matt" };
        formatter.WriteObject(stream, instance);

        stream.Seek(0, SeekOrigin.Begin);

        var second = (TestClass2)formatter.ReadObject(stream);
        Console.WriteLine(second.Name);
    }
}

OUTPUT: "MATT"

And with a DataContractAttribute:

[DataContract, Serializable]
public class TestClass3
{
    public int Age { get; set; }

    [DataMember]
    public string Name { get; set; }
}

{
    var formatter = new DataContractSerializer(typeof(TestClass3));
    using (var stream = new MemoryStream())
    {
        var instance = new TestClass3 { Name = "Matt", Age = 26 };
        formatter.WriteObject(stream, instance);

        stream.Seek(0, SeekOrigin.Begin);

        var second = (TestClass3)formatter.ReadObject(stream);
        Console.WriteLine(second.Name);
        Console.WriteLine(second.Age);
    }
}

OUTPUT: "Matt"

OUTPUT: 0

When the DataContractSerializer encounters a type with a DataContractAttribute, it will use that instead of passing serialization to its base type, which handles the SerializableAttribute and ISerializable interfaces.

If you are encountering issues, is it with serialisation, or with deserialisation, or both?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!