【发布时间】:2019-08-29 20:40:37
【问题描述】:
我正在使用 .net Core 1.1 并编写控制台应用程序。我需要使用字符串和 int 的一些基本属性以及一些 IEnumerable 对象来序列化一个对象,并将其序列化为 XML,以便将其保存到“data.xml”文件中。
我收到异常: System.Runtime.Serialization.SerializationException: 'Type 'System.Collections.Generic.List`1[[CorpsDataExtractor.ViewModels.LegacyView, CorpsDataExtractor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' with data contract name 'ArrayOfLegacyView:http://schemas.datacontract.org/2004/07/CorpsDataExtractor.ViewModels' 不是预期的。将任何静态未知的类型添加到已知类型列表中 - 例如,通过使用 KnownTypeAttribute 属性或将它们添加到传递给 DataContractSerializer 的已知类型列表中。'
我目前能够将我的对象序列化为 JSON,但在使用 DataContractSerializer 时遇到问题。我添加了异常状态的已知类型列表,但它仍然失败。
// This List isretrieved using Entity Framework Core
List<LegacyView> legacyData = await _corpsRepo.ListLegacyData();
// The Below Line will write to a JSON File. No Error and works
File.WriteAllText(@"E:\\CorporationsDataLegacy.json", JsonConvert.SerializeObject(legacyData));
// This Creates a Known Type List for the DataContractSerializer
var knownTypeList = new List<Type>
{
typeof(LegacyView),
typeof(People),
typeof(DocumentType)
};
FileStream writer = new FileStream(@"E:\\data.xml", FileMode.Create);
var ser = new DataContractSerializer(typeof(LegacyView), knownTypeList );
// When Debugging I Receive The stated exception at this line
ser.WriteObject(writer, legacyData);
以下是我的类 ViewModel:
旧版视图
[DataContract]
public class LegacyView
{
[DataMember]
public string Ubi { get; set; }
[DataMember]
public IEnumerable<Person> People{ get; set; }
[DataMember]
public IEnumerable<DocumentType> DocumentTypes { get; set; }
}
人物
[DataContract]
public class Person
{
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string MiddleName { get; set; }
}
文档
[DataContract]
public class DocumentType
{
[DataMember]
public string Document { get; set; }
[DataMember]
public DateTime? CompletedDate { get; set; }
}
关于我缺少什么的任何指示?
【问题讨论】:
-
您是否尝试将
typeof(IEnumerable<People>), typeof(IEnumerable<DocumentType>)添加到已知类型? -
@Gusman,结合使用你的答案和答案,我将我的属性保留为 IEnumerable 但是我声明了我的 KnownType List 我需要使用 List
来制作这些具体 -
很高兴你能成功。添加您的解决方案作为答案,因为这可以帮助其他人解决您的相同问题。
标签: c# xml xml-serialization .net-core