我正在尝试转换一个对象,即将具有多个字段的用户转换为XML。问题是我在尝试序列化ILIST成员时遇到异常。 以下是我正在使用的代码:
var stringwriter = new System.IO.StringWriter();
var serializer = new XmlSerializer(User.GetType()); <!-- Getting exception here -->
serializer.Serialize(stringwriter, User);
return stringwriter.ToString();
我的用户看起来像这样:
class User
{ public virtual string Name{ get; set; }
public virtual DateTime? LastUpdated { get; set; }
public virtual int? ContactId { get; set; }
public virtual IList<Sector> Sectors { get; set; }
public virtual AccessLevel AccessLevel { get; set; }
public virtual IList<UserRole> UserRole { get; set; }
}
有没有办法可以检查我正在序列化的对象的类成员是否可序列化,然后调整该特定成员的逻辑。我对用户类的控制较少。 :(所以任何我可以扩展我的代码来处理IList成员的方式将是首选。
答案 0 :(得分:5)
旧式XML序列化无法处理接口 - 它需要具体的类型。
但是,您可以使用较新的DataContractSerializer
。
以下是基于您的代码的示例:
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;
namespace Demo
{
[DataContract(Namespace = "")]
public class User
{
[DataMember]
public virtual string Name
{
get;
set;
}
[DataMember]
public virtual DateTime? LastUpdated
{
get;
set;
}
[DataMember]
public virtual int? ContactId
{
get;
set;
}
[DataMember]
public virtual IList<string> Sectors
{
get;
set;
}
}
internal class Program
{
private void run()
{
User user = new User();
user.Sectors = new[] {"One", "Two", "Three"};
user.Name = "Test Name";
// Serialize
var result = new StringBuilder();
DataContractSerializer serializer = new DataContractSerializer(user.GetType());
using (var stringWriter = new StringWriter(result))
using (var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings { Indent = true } ))
{
serializer.WriteObject(xmlWriter, user);
}
string serialisedToString = result.ToString();
Console.WriteLine(serialisedToString);
// Deserialize
using (var stringReader = new StringReader(serialisedToString))
using (var xmlReader = XmlReader.Create(stringReader))
{
user = (User) serializer.ReadObject(xmlReader);
}
Console.WriteLine(user.Name);
}
private static void Main()
{
new Program().run();
}
}
}