C#:为什么实现Serializable的对象无法序列化?

时间:2012-01-20 15:48:50

标签: c# serialization

我正在运行桌面应用程序,当我到达此行时:

serializer.Serialize(new StringWriter(sb), value);

它会引发以下错误:

There was an error generating the XML document.

这是代码:

public static string Serialize(object value)
    {
        var serializer = new XmlSerializer(value.GetType());
        var sb = new StringBuilder();
        serializer.Serialize(new StringWriter(sb), value);
        return sb.ToString();
    }

当我调试时,我会在Watch部分看到这个:

    value.GetType().IsSerializable  true    bool

我在声明 values 的类之前设置了这个:

[Serializable]

提前谢谢。

例外细节

            System.InvalidOperationException was unhandled by user code
              Message="There was an error generating the XML document."
              Source="System.Xml"
              StackTrace:
                   at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
                   at System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o, XmlSerializerNamespaces namespaces)
                   at System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o)
                   at Pacer.PIA.UI.WindowsForms.Controls.Utility.Serialize(Object value) in E:\Projects\Indexing\Main\Source\Pacer.PIA\Source\Pacer.PIA.UI.WindowsForms\Controls\Utility.cs:line 55
                   at Pacer.PIA.UI.WindowsForms.Controller.MainForm.ActionLoad..ctor(Int32[] index, Object objValue) in E:\Projects\Indexing\Main\Source\Pacer.PIA\Source\Pacer.PIA.UI.WindowsForms\Controller\MainForm\ActionAdd.cs:line 37
                   at Pacer.PIA.UI.WindowsForms.MainForm.SearchLoadByLoadNumber(String loadNumber) in E:\Projects\Indexing\Main\Source\Pacer.PIA\Source\Pacer.PIA.UI.WindowsForms\Forms\MainForm.cs:line 3530
                   at Pacer.PIA.UI.WindowsForms.MainForm.rmedtLoadNumber_KeyPress(Object sender, KeyPressEventArgs e) in E:\Projects\Indexing\Main\Source\Pacer.PIA\Source\Pacer.PIA.UI.WindowsForms\Forms\MainForm.cs:line 1244
                   at Telerik.WinControls.RadItem.OnKeyPress(KeyPressEventArgs e)
                   at Telerik.WinControls.UI.RadTextBoxElement.textBoxItem_KeyPress(Object sender, KeyPressEventArgs e)
                   at Telerik.WinControls.RadItem.OnKeyPress(KeyPressEventArgs e)
                   at Telerik.WinControls.UI.RadTextBoxItem.TextBoxControl_KeyPress(Object sender, KeyPressEventArgs e)
                   at System.Windows.Forms.Control.OnKeyPress(KeyPressEventArgs e)
                   at Telerik.WinControls.UI.RadMaskTextBox.OnKeyPress(KeyPressEventArgs e)
                   at System.Windows.Forms.Control.ProcessKeyEventArgs(Message& m)
                   at System.Windows.Forms.Control.ProcessKeyMessage(Message& m)
                   at System.Windows.Forms.Control.WmKeyChar(Message& m)
                   at System.Windows.Forms.Control.WndProc(Message& m)
                   at System.Windows.Forms.TextBoxBase.WndProc(Message& m)
                   at System.Windows.Forms.TextBox.WndProc(Message& m)
                   at Telerik.WinControls.UI.HostedTextBoxBase.WndProc(Message& message)
                   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
                   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
                   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
              InnerException: System.InvalidOperationException
                   Message="The type System.Drawing.Bitmap was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically."
                   Source="niumy1xe"
                   StackTrace:
                        at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterBELoadCollection.Write4_Image(String n, String ns, Image o, Boolean isNullable, Boolean needType)
                        at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterBELoadCollection.Write5_BEDocument(String n, String ns, BEDocument o, Boolean isNullable, Boolean needType)
                        at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterBELoadCollection.Write6_BERequirement(String n, String ns, BERequirement o, Boolean isNullable, Boolean needType)
                        at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterBELoadCollection.Write8_BEMove(String n, String ns, BEMove o, Boolean isNullable, Boolean needType)
                        at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterBELoadCollection.Write9_BELoad(String n, String ns, BELoad o, Boolean isNullable, Boolean needType)
                        at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterBELoadCollection.Write10_ArrayOfBELoad(Object o)
                   InnerException:

班级:

    [Serializable]
public class BELoadCollection : List<BELoad>, ICloneable
{
    public BELoad FindByLoadId(string loadId)
    {
        return this.Find(load => load.LoadId.Equals(loadId));
    }

    public bool ExistsByLoadId(string loadId)
    {
        return this.Exists(load => load.LoadId.Equals(loadId));
    }

    public bool HasLoadsWithDocumentRequirementLinked
    {

        get
        {
            return this.Exists(load => load.HasDocumentsRequirementLinked);
        }
    }

    public void PrepareRequirementsToIndex()
    {
        this.ForEach(load =>
        {
            load.PrepareRequirementsToIndex();
        });

    }

    public bool HasLoadsReadyToIndex
    {

        get
        {
            return this.Exists(load => load.HasDocumentsRequirementReadyToIndex);
        }

    }

    public BERequirementCollection GetRequirementsReadyToIndex()
    {
        BERequirementCollection beRequirementsReadyToIndex = new BERequirementCollection();

        this.ForEach(load => beRequirementsReadyToIndex.AddRange(load.GetRequirementsReadyToIndex()));

        return beRequirementsReadyToIndex;
    }

    #region ICloneable Members

    object ICloneable.Clone()
    {
        return this.Clone();
    }

    public BELoadCollection Clone()
    {
        BELoadCollection BELoadCollectionClone = new BELoadCollection();

        for (int i = 0; i <= this.Count - 1; i++)
            BELoadCollectionClone.Add(this[i]);

        return BELoadCollectionClone;
    }

    #endregion
}

这是BELoad(只是田野)

 public class BELoad : BEMetaData, ICloneable
{
    //Fields
    private BEMoveCollection beMoveCollection;

    public string LoadId { get; set; }
    public string Description { get; set; }
    public string DocumentType { get; set; }
    public string Vendor { get; set; }
    public string VendorCityState { get; set; }
    public string State { get; set; }
    public string EquipmentPrefix { get; set; }
    public string EquipmentNumber { get; set; }
    public string Driver { get; set; }
    public string Shipper { get; set; }
    public string ShipperCityState { get; set; }
    public string BillTo { get; set; }
    public string BillToCityState { get; set; }
    public string Consignee { get; set; }
    public string ConsigneeCityState { get; set; }
    public string Stop { get; set; }
    public string StopCityState { get; set; }
    public string Container { get; set; }
}

3 个答案:

答案 0 :(得分:6)

stacktrace中有一个提示:

InnerException: System.InvalidOperationException                    
    Message="The type System.Drawing.Bitmap was not expected. 
    Use the XmlInclude or SoapInclude attribute to specify types 
    that are not known statically." 

System.Drawing.Bitmap不是Xml Serializable,因此是例外。也许另一种方法是使用XmlIgnoreAttribute来忽略这个属性,或者实现IXmlSerializable并将图像序列化为ascii blob,如果你确实需要它保存的话?

  

查看相关问题&amp;回答Serializing a Bitmap in C# to XML

由Conrad Frix在评论

中提供

答案 1 :(得分:2)

Serializable属性与XML序列化无关,它用于二进制序列化。使用BinaryFormatter序列化的对象并不总是可以使用XmlSerializer ...

进行序列化

答案 2 :(得分:0)

对于XMLSerializer,您必须在类中进行序列化的无参数构造。

请注意,BinaryFormatter和DataContractSerializer不需要这样做 - 他们可以在以太网中创建一个未初始化的对象,并在反序列化期间初始化它。