在我的代码中,我必须序列化 List< IModel> ,其中 IModel 是具体类的接口模型
以下是一些伪代码:
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&lt; InterfaceName&gt;时,是否有另一种方法可以轻松地序列化列表?虽然它包含实现该接口的唯一具体类的元素?我尝试了一些演员,但我得到了编译错误或运行时异常。
我想指出,在我之前的实现中,我将 List&lt; IModel&gt; 中的所有项目复制到 List&lt; Model&gt; 中,这是DataContractJsonSerializer已知的类型。事实上,我确信任何 IModel 都是模型。
答案 0 :(得分:0)
为什么需要任何此类实现的接口?
我建议你通过http://json2csharp.com/为你的JSON生成C#类。完成后,粘贴这些类并找到<RootObject>
类,然后使用您在问题中提到的code
对其进行序列化
答案 1 :(得分:0)
这是AutoMapper的解决方案。我通过向http_keepalive_timeout
添加私有设置器来更改您实现的类。我希望你的确可以。
Position
接口:
List<IModel> sourceList = new List<IModel> {new Model("A", 1), new Model("B", 2)};
AutoMapper.Mapper.Initialize(a => a.CreateMap<IModel, Model>());
List<Model> targetList = AutoMapper.Mapper.Map<List<IModel>, List<Model>>(sourceList);
AutoMapper.Mapper.Initialize(a =>
{
a.CreateMap<Model, Model>();
a.CreateMap<Model, IModel>().ConstructUsing(Mapper.Map<Model, Model>);
});
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(List<Model>), new[] { typeof(Model) });
using (FileStream writer = File.Create(@"c:\temp\modello.json"))
{
jsonSerializer.WriteObject(writer, targetList);
}
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(List<Model>));
MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(File.ReadAllText(@"c:\temp\modello.json")));
List<Model> targetListFromFile = (List<Model>)js.ReadObject(ms);
List<IModel> sourceListFromFile = AutoMapper.Mapper.Map<List<Model>, List<IModel>>(targetListFromFile);
类别:
public interface IModel
{
string Codice { get; set; }
int Position { get; }
}
该文件如下所示:
[DataContract]
public class Model : IModel
{
public Model(string Codice, int position)
{
this.Codice = Codice;
Position = position;
}
[DataMember(Name = "codice")]
public string Codice { get; set; }
[DataMember(Name = "position")]
public int Position { get; private set; }
}