CuriousDev
CuriousDev

Reputation: 49

How to serialize xml date value to DateTime class in c#

I am passing the following xml

<PolicyNumber>6456365A1</PolicyNumber>
<EffectiveDate>2015-10-01T00:00:00</EffectiveDate>
<ExpirationDate>2016-10-01T00:00:00</ExpirationDate>

to class through fiddler post.But the Values in the following class

    [DataContract]
    public class Parameter
    {
        [DataMember]
        public string PolicyNumber { get; set; }
        [DataMember] 
        public DateTime EffectiveDate { get; set; }
        [DataMember]
        public DateTime ExpirationDate { get; set; }
    }

The value for policy number getting passed as expected.The value for DateTime is not getting passed instead it has its default value. I am posting it using fiddler to web api mvc.

enter image description here

Upvotes: 0

Views: 560

Answers (2)

Charles Mager
Charles Mager

Reputation: 26233

The order is wrong here. DataContractSerializer will use alphabetical order unless you specify otherwise (see the docs), so it's expecting EffectiveDate, ExpirationDate, and then PolicyNumber.

You need to either re-arrange your XML to be in that order, or you need to specify the order on the class via attributes:

[DataContract]
public class Parameter
{
    [DataMember(Order = 0)]
    public string PolicyNumber { get; set; }
    [DataMember(Order = 1)]
    public DateTime EffectiveDate { get; set; }
    [DataMember(Order = 2)]
    public DateTime ExpirationDate { get; set; }
}

Upvotes: 1

Clayton Singh
Clayton Singh

Reputation: 50

You can simply make it a private member that is only used for serialization.

[DataContract]
public class AutoIDCardParameter
{
    [DataMember(Name = "PolicyNumber")]
    public string PolicyNumber;

    [DataMember(Name = "EffectiveDate")]
    private string _EffectiveDate {
        get {
            return EffectiveDate.ToString("yyyy-MM-DDTHH:mm:ss");
        }
        set {
            DateTime.TryParse(value, out EffectiveDate);
        }
    }

    public DateTime EffectiveDate;

    // ....
}

Upvotes: 1

Related Questions