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.