0

我有一个应用程序需要序列化自定义对象并将其发送到 Windows 服务,自定义对象包含 2 个自定义对象列表和一个 int、string 字典。当我尝试序列化对象时,我收到错误消息:

There was an error generating the XML document.

我搜索了一下,发现这通常是由于没有正确设置序列化的数据类型之一。所以我已经完成并验证了所有自定义类的序列化,并且据我所知它设置正确。

我现在的问题是,默认情况下列表和字典是可序列化的,还是需要做些什么才能序列化它们?或者,是否有更好的方法来序列化要在可执行文件之间传递的自定义对象集合?

编辑:

主要自定义类:

[Serializable]
class MoveInInfoRequest : ServerRequestData
{ }
[Serializable]
[XmlInclude(typeof(GetUnitTypesResponseData)), XmlInclude(typeof(VendorObj.RequiredFields)),
     XmlInclude(typeof(VendorObj.InsuranceChoice)), XmlInclude(typeof(VendorObj.ProrateSettings))]
public class MoveInInfoResponse : ServerResponseData
{
    public GetUnitTypesResponseData UnitTypesInfo
    { get; set; }
    public List<VendorObj.RequiredFields> RequiredFields 
    { get; set; }
    public Dictionary<int, String> RentalPeriods
    { get; set; }
    public List<VendorObj.InsuranceChoice> InsCoverageAmounts
    { get; set; }
    public VendorObj.ProrateSettings ProrateOptions
    { get; set; }
}

示例子类:其他两个类的设置与此类似,只是时间更长,但它们仅使用默认数据类型。

<Serializable(), DataContract([Namespace]:="*companyNamespace*")> _
Public Class InsuranceChoice
    Public Sub New()
    End Sub
    <DataMember()> _
    Public InsuranceChoiceID As Integer
    <DataMember()> _
    Public CoverageDescription As String
    <DataMember()> _
    Public Premium As Decimal
    <DataMember()> _
    Public ActualCoverageAmount As Decimal

End Class
4

2 回答 2

1

It depends on what you are trying to serialize them with. In particular, Dictionary objects are not serializable if you are using XmlSerializer, though they are if you are using DataContractSerializer. You should be fine to serialize a List.

If you would like an alternative to Xml serialization, you could serialize to JSON using Json.Net.

References:

Serialize Class containing Dictionary member

Serializing .NET dictionary

Why doesn't XmlSerializer support Dictionary?

http://theburningmonk.com/2010/05/net-tips-xml-serialize-or-deserialize-dictionary-in-csharp/

于 2012-11-07T20:41:03.433 回答
1

当涉及到序列化时,这是一个很常见的问题。

集合实现IDictionary 无法序列化

您可以使用DataContractSerializer,但更好的解决方案(在我看来)是创建自己的 Dictionary 类,该类不继承自IDictionary

可以在此处找到此类的示例

在解决方案中实现类后,只需执行以下操作:

using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var response = new MoveInInfoResponse
            {
                RentalPeriods = new SerializableDictionary<int, string> 
                { { 1, "Period 1" }, { 2, "Period 2" } }
            };

            string xml = Serialize(response);
        }

        static string Serialize(Object obj)
        {
            var serializer = new XmlSerializer(obj.GetType());
            var settings = new XmlWriterSettings { Indent = true, OmitXmlDeclaration = true };

            using (var stream = new StringWriter())
            {
                using (var writer = XmlWriter.Create(stream, settings))
                    serializer.Serialize(writer, obj);
                return stream.ToString();
            }
        }
    }

    [Serializable]
    public class MoveInInfoResponse
    {
        public SerializableDictionary<int, String> RentalPeriods
        { get; set; }
    }
}

生成以下 XML 文件:

<MoveInInfoResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <RentalPeriods>
    <Item>
      <Key>
        <int>1</int>
      </Key>
      <Value>
        <string>Period 1</string>
      </Value>
    </Item>
    <Item>
      <Key>
        <int>2</int>
      </Key>
      <Value>
        <string>Period 2</string>
      </Value>
    </Item>
  </RentalPeriods>
</MoveInInfoResponse>
于 2012-11-07T20:58:43.590 回答