DataContractSerializer serializes interface properties as System.Object / anyType

In the application, I have the following interface / implementation structure:

public interface IMyInterface { IMyOtherInterface InstanceOfMyOtherInterface { get; } } public interface IMyOtherInterface { string SomeValue { get; } } [DataContract(Name = "MyInterfaceImplementation", Namespace = "")] public class MyInterfaceImplementation : IMyInterface { [DataMember(EmitDefaultValue = false), XmlAttribute(Namespace = "")] public IMyOtherInterface InstanceOfMyOtherInterface { get; private set; } public MyInterfaceImplementation() { this.InstanceOfMyOtherInterface = new MyOtherInterfaceImplementation("Hello World"); } } [DataContract(Name = "MyOtherInterfaceImplementation", Namespace = "")] public class MyOtherInterfaceImplementation : IMyOtherInterface { [DataMember] public string SomeValue { get; private set; } public MyOtherInterfaceImplementation(string value) { this.SomeValue = value; } } 

Now when I use .Net DataContractSerializer to serialize this (in my case to a string) as follows:

 var dataContractSerializer = new DataContractSerializer(typeof(MyInterfaceImplementation)); var stringBuilder = new StringBuilder(); using (var xmlWriter = XmlWriter.Create(stringBuilder, new XmlWriterSettings { Indent = true, Encoding = Encoding.UTF8 })) { dataContractSerializer.WriteObject(xmlWriter, this); } var stringValue = stringBuilder.ToString(); 

the resulting xml looks something like this:

 <?xml version="1.0" encoding="utf-16"?> <z:anyType xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="" i:type="MyInterfaceImplementation" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/"> <InstanceOfMyOtherInterface xmlns="" i:type="InstanceOfMyOtherInterface"> <SomeValue>Hello World</SomeValue> </InstanceOfMyOtherInterface> </z:anyType> 

These * anyType * s seem to come from a datacontractserializer, serializing an instance of MyInterfaceImplementation as System.Object, similar to other interface properties.

If I used specific types in my interface and its implementation (s) as follows:

 public interface IMyInterface { MyOtherInterface InstanceOfMyOtherInterface { get; } } 

.. it works "fine", as in - the datacontractserializer creates

 <MyInterfaceImplementation>...</MyInterfaceImplementation> 

... instead of z: anyType, but I do not want / cannot change the properties of my interfaces. Is there a way to control or help the data serializer in such cases?

+4
source share

Source: https://habr.com/ru/post/1445153/


All Articles