DataContractJsonSerializer和列表
问题描述:
在我的代码必须序列列表<IModel>其中IModel是具体类型号DataContractJsonSerializer和列表<Interface>
这里的接口是他们一些伪代码:
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”。 当列表声明为列表<InterfaceName>时,是否有另一种轻松地序列化列表的方法,但它包含实现该接口的唯一具体类的元素?我尝试了一些强制转换,但是出现了编译错误或运行时异常。
我想指定我在以前执行我复制的所有项目从列表<IModel>到列表<型号>这是已知DataContractJsonSerializer类型。实际上,我确信任何IModel是模型。
答
为什么你需要一个用于任何这种实现的接口? 我建议你通过http://json2csharp.com/为你的JSON生成C#类。完成后,粘贴这些类并找到<RootObject>
类,然后使用您在问题中提到的code
将其序列化。
答
这是AutoMapper的解决方案。我已经通过向Position
添加专用setter来更改实施的课程。我希望这对你有好处。
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; }
}
文件看起来是这样的:
[{
"codice": "A",
"position": 1
},
{
"codice": "B",
"position": 2
}]
为什么不序列化的具体类?在这种情况下使用接口的目的是什么? – Ben
也许试试这个:https://stackoverflow.com/questions/8513042/json-net-serialize-deserialize-derived-types – Jodn
@Ben界面创建了一层抽象,现在所有的代码使用该界面,而不是的实施班。目前它被写入它似乎是一个好主意,现在它在那里,但它不是绝对必要的 – Filippo