I have a .Net Maui Hybrid project that calls an API that returns XML. The API returns the xml and I Deserialize to an object using code below:
var serializer = new XmlSerializer(typeof(List<FullQuoteResponseModel>));
var annuityIncomes = (List<FullQuoteResponseModel>)serializer.Deserialize(new StringReader(xml));
This works correctly when I run in Windows however when I deploy to Android the Deserialize fails with following error: String '28-05-2024' was not recognized as a valid DateTime.
The date in the xml looks like:
<expiry_date>28-04-2024</expiry_date>
In my object I have serialization attributes to handle as shown below this that work in Windows but fails in Android
[XmlIgnore]
public DateTime? ExpiryDate { get; set; }
[XmlElement("expiry_date", IsNullable = true)]
public string ExpiryDateString
{
get
{
DateTime? expiryDate = this.ExpiryDate;
ref DateTime? local = ref expiryDate;
return !local.HasValue ? (string) null : local.GetValueOrDefault().ToString("dd-MM-yyyy");
}
set
{
this.ExpiryDate = value == null ? new DateTime?() : new DateTime?(DateTime.Parse(value));
}
}
Why is this failing in Android but now windows?
I found the answer myself, Jason's comment about local led me to the answer. In Windows not setting the local didn't affect the Deserialization and dates with UK format dd-MM-yyyy still worked (not sure why).
However in Android Deserialization of UK formatted dates in the response resulted in the error below which I understand i.e. its an invalid date format for the default culture which was en-US
String '28-05-2024' was not recognized as a valid DateTime
To resolve this problem I changed the current culture to en-GB in the MainActivity.cs for the Android platform as below:
private void SetLocale()
{
CultureInfo ci = new CultureInfo("en-GB");
CultureInfo.DefaultThreadCurrentCulture = ci;
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
}
Desirialization now picked up the dates as the correct format. Hope this helps someone