views:

136

answers:

2

I have a third party web service that returns this xml

<book>
  <release_date>0000-00-00</release_date>
</book>

I am trying to deserialize it into this class

public class Book
{
    [XmlElement("release_date")]
    public DateTime ReleaseDate { get; set; }
}

But because 0000-00-00 isn't a valid DateTime, I get a FormatException. What's the best way to handle this?

+3  A: 

If the 3rd party schema defines that field as datetime, then it should always contain a valid datetime value unless something goes wrong. In this case, you may consider to deserialize it as a string

public class Book
{
    [XmlElement("release_date")]
    public string ReleaseDate { get; set; }

    public DateTime? GetReleaseDate 
    { 
      get 
      {
           // parse ReleaseDate datetime string
           // return the value; or null if the string contains invalid datetime.
      }
    }
}
codemeit
third party isn't .net so not necessarily a DateTime, hence the 0000-00-00. The string approach you suggested is what I also did but it feels hacky and hoped there might be a cleaner solution
qntmfred
What type of release_date is described in the WSDL? string? or there is no WSDL, in this case, it should be deserialized as string first and then apply your own logic I am afraid.
codemeit
+1  A: 
public class Book
{
    [XmlElement("release_date")]
    public string StringReleaseDate
    {
        get {return ReleaseDate.ToString("yyyy-MM-dd");}
        set {ReleaseDate = DateTime.ParseExact(value, "yyyy-MM-dd");}
    }

    [XmlIgnore]
    public DateTime ReleaseDate {get;set;}
}
John Saunders