gpt4 book ai didi

c# - .Net Core 使用 IEnumerables 序列化对象以另存为 XML

转载 作者:行者123 更新时间:2023-11-30 23:11:55 26 4
gpt4 key购买 nike

我正在使用 .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]]' 数据协定名称'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);

下面是我的类 ViewModels:

旧 View

[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; }
}

关于我遗漏的任何方向?

最佳答案

我可能有点偏离,因为我已经完成了更多的 XmlSerialize 而不是 DataContracts,但我相信两者都假定内容最终反序列化。和 IEnumerable<T>作为类型,反序列化器不知道在反序列化期间实际实例化哪个类来支持接口(interface)。将字段更改为具体类而不是枚举,这应该有效。

关于c# - .Net Core 使用 IEnumerables<T> 序列化对象以另存为 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44446594/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com