序列化.NET对象时缺少字段

时间:2011-05-03 21:12:42

标签: c# .net serialization xml-serialization

我在使用C#序列化对象时遇到问题。当应用程序进行序列化对象时,某些字段会被序列化,但其他字段则不会。在以下代码中:

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class ACORDInsuranceSvcRqHomePolicyQuoteInqRq
{

    private string rqUIDField;

    private System.DateTime transactionRequestDtField;

    private System.DateTime transactionEffectiveDtField;

    private string curCdField;

    /// <remarks/>
    public string RqUID
    {
        get
        {
            return this.rqUIDField;
        }
        set
        {
            this.rqUIDField = value;
        }
    }

    /// <remarks/>
    public string CurCd
    {
        get
        {
            return this.curCdField;
        }
        set
        {
            this.curCdField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlIgnore()]
    public System.DateTime TransactionRequestDt
    {
        get
        {
            return this.transactionRequestDtField;
        }
        set
        {
            this.transactionRequestDtField = value;
        }
    }

    /// <remarks/>
    [XmlElement("TransactionRequestDt")]
    public string TransactionRequestDtString
    {
        get
        {
            return String.Format("{0:yyyy-MM-dd}", this.TransactionRequestDt);
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlIgnore]
    public System.DateTime TransactionEffectiveDt
    {
        get
        {
            return this.transactionEffectiveDtField;
        }
        set
        {
            this.transactionEffectiveDtField = value;
        }
    }

    /// <remarks/>
    [XmlElement("TransactionEffectiveDt")]
    public string TransactionEffectiveDtString
    {
        get
        {
            return String.Format("{0:yyyy-MM-dd}", this.TransactionEffectiveDt);
        }
    }
}

你可以看到Fields / Accessors RqUID和CurCd被调用但是TransactionRequestDtString和TransactionEffectiveDtString却没有。我需要将所有这些序列化。谢谢!

3 个答案:

答案 0 :(得分:6)

如果需要进行xml序列化,则需要公开获取并设置。

尝试将代码更改为:

[ReadOnly(true)]
[XmlElement("TransactionRequestDt")]
public string TransactionRequestDtString
{
    get
    {
        return String.Format("{0:yyyy-MM-dd}", this.TransactionRequestDt);
    }
    set{}
}`

ReadOnly属性不允许任何人更改它。

答案 1 :(得分:1)

可能的答案请参阅:Serializing private member data

答案 2 :(得分:0)

我遇到了一些属性(可以为空)的问题,我通过使用以下方法修复它:[XmlElement(IsNullable = true)] decorator

公共类人员 {

[XmlElement(IsNullable = true)] public string Name {get;组; } }