【发布时间】:2017-07-25 11:15:27
【问题描述】:
在我的代码中,我必须序列化 List
这里是他们的一些伪代码:
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; } }
}
看完this post我写道:
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(List<IModel>), new[] { typeof(Model) });
using (FileStream writer = File.Create(@"c:\temp\modello.json"))
{
jsonSerializer.WriteObject(writer, myList);
}
它可以工作,但很难看,输出包含元素类型的字段,"__type":"Model:#SomeProjectName"。
当列表声明为 List
我想说明,在我之前的实现中,我将所有项目从 List
【问题讨论】:
-
为什么不序列化具体类呢?这种情况下使用接口的目的是什么?
-
@Ben 该接口被创建为具有抽象层,现在所有代码都使用该接口而不是实现类。在写它的那一刻,这似乎是一个好主意,现在它就在那里,但它不是绝对必要的
-
您之前的实现有什么问题?我只是想了解你的想法:)
标签: c# datacontractjsonserializer