How to use DataContractSerializer with Binder

Deepak Rane (drane) 60 Reputation points
2024-12-22T08:01:24.79+00:00

Hi Team,

We are converting BinaryFormatter to DataContractSerializer in our code.

With BinaryFormatter we had used Binder property , How can we convert that with DataContractSerializer?

Sample:

var bf = new BinaryFormatter();

bf.Binder = new ClassXYZ();//ClassXYZ inherited from SerializationBinder

var dc = (Class2)bf.Deserialize(stream);

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,152 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Jiale Xue - MSFT 48,441 Reputation points Microsoft Vendor
    2024-12-23T01:58:59.61+00:00

    Hi @Deepak Rane (drane) , Welcome to Microsoft Q&A,

    The Binder property in BinaryFormatter allows you to control type resolution during deserialization. However, DataContractSerializer does not directly support this feature. Try to use a custom DataContractResolver.

    using System;
    using System.IO;
    using System.Runtime.Serialization;
    
    public class CustomResolver : DataContractResolver
    {
        public override Type ResolveName(string typeName, string typeNamespace, Type declaredType, DataContractResolver knownTypeResolver)
        {
            // Custom logic to map serialized type name to actual type
            if (typeName == "ClassXYZ" && typeNamespace == "http://yournamespace/")
            {
                return typeof(ClassXYZ); // Map serialized name to actual type
            }
    
            // Default resolution
            return knownTypeResolver.ResolveName(typeName, typeNamespace, declaredType, null);
        }
    
        public override bool TryResolveType(Type type, Type declaredType, DataContractResolver knownTypeResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace)
        {
            var dictionary = new XmlDictionary();
    
            // Custom logic to map actual type to serialized type name
            if (type == typeof(ClassXYZ))
            {
                typeName = dictionary.Add("ClassXYZ");
                typeNamespace = dictionary.Add("http://yournamespace/");
                return true;
            }
    
            // Default resolution
            return knownTypeResolver.TryResolveType(type, declaredType, null, out typeName, out typeNamespace);
        }
    }
    
    [DataContract]
    public class Class2
    {
        [DataMember]
        public string Property { get; set; }
    }
    
    [DataContract]
    public class ClassXYZ
    {
        [DataMember]
        public int Value { get; set; }
    }
    
    class Program
    {
        static void Main()
        {
            var stream = new MemoryStream();
            var instance = new Class2 { Property = "Test" };
    
            // Serialize using DataContractSerializer
            var serializer = new DataContractSerializer(typeof(Class2), null, int.MaxValue, false, true, null, new CustomResolver());
            serializer.WriteObject(stream, instance);
    
            stream.Position = 0;
    
            // Deserialize using DataContractSerializer
            var deserializer = new DataContractSerializer(typeof(Class2), null, int.MaxValue, false, true, null, new CustomResolver());
            var result = (Class2)deserializer.ReadObject(stream);
    
            Console.WriteLine($"Deserialized Property: {result.Property}");
        }
    }
    
    

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.