I am using DataContractJsonSerializer.
Currently, my serialized object contained a member of class "Settings"
Now, I would like to extend my support and serialize any class that implements ISettings interface.
[DataContract(Namespace = "")]
[KnownType(typeof(SystemSettings))]
[KnownType(typeof(PrivateSettings))]
public class Data
{
[DataMember]
public ISettings settings { get; set; }
}
public interface ISettings
{
}
[DataContract(Namespace = "")]
public class SystemSettings : ISettings
{
[DataMember]
public string Name { get; set; }
[DataMember]
public string SysName { get; set; }
}
[DataContract(Namespace = "")]
public class PrivateSettings : ISettings
{
[DataMember]
public string Name { get; set; }
[DataMember]
public string PrivateName { get; set; }
}
This works perfectly fine, as the serialized data contains the type of the object
<?xml version="1.0" encoding="utf-8"?>
<root type="object">
<settings __type="SystemSettings" type="object">
<Name>System Settings</Name>
<SysName>New System</SysName>
</settings>
</root>
My issue is with backward compatibility. The existing serialized files do not contain the object type (__type="SystemSettings"). When deserializing old data into my class, I get
"{"Unable to cast object of type 'System.Object' to type 'JsonSerializer.ISettings'."}"
Is there a way to solve this? Can I direct the serializer what default type to instantiate for the interface?
Thank you!