In my code I have to serialize List<IModel> where IModel is the interface for concrete class Model
Here is some pseudo code for them:
public interface IModel
{
string Codice { get; set; }
int Position { get; }
}
[DataContract]
public class Model : IModel
{
public Model(string Codice, int position)
{
this.Codice = Codice;
this.position = position;
}
[DataMember(Name = "codice")]
public string Codice { get; set; }
[DataMember(Name = "position")]
int position;
public int Position { get { return position; } }
}
After reading this post I wrote:
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(List<IModel>), new[] { typeof(Model) });
using (FileStream writer = File.Create(@"c:\temp\modello.json"))
{
jsonSerializer.WriteObject(writer, myList);
}
It works but it is ugly and the output contains a field for the type of the element, "__type":"Model:#SomeProjectName". Is there another way to easily serialize a list when it is declared as List<InterfaceName> while it contains elements of the only concrete class that implement that interface ? I tried with some casts but I got compilation error or runtime exceptions.
I would like to specify that in my previous implementation I copied all items from List<IModel> into List<Model> which was the type known to DataContractJsonSerializer. In fact I'm sure that any IModel is a Model.