I am using .net Core 1.1 and writing a console application. I need to Serialize an Object with some basic properties of strings and int as well as some IEnumerable Objects and serialize it as XML so I can save it to a "data.xml" file.
I receive the Exception: 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' is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.'
I currently am able to serialize my Object as JSON, but am having trouble utilizing the DataContractSerializer. I Added the Known Type List that the exception states I am missing but it still fails.
// 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);
Below Are my Class ViewModels:
Legacy 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; }
}
Person
[DataContract]
public class Person
{
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string MiddleName { get; set; }
}
Documents
[DataContract]
public class DocumentType
{
[DataMember]
public string Document { get; set; }
[DataMember]
public DateTime? CompletedDate { get; set; }
}
Any Direction on what I am missing?