XmlMediaTypeFormatter not handeling DateTimeOffset properties?

Topics: ASP.NET Web API
May 14, 2012 at 8:13 PM

I am noticing that my resources with DateTimeOffset properties are showing nicely in JSON but not in XML...In XML I get an empty xml node for example: <DateSold />. Is anyone experiencing the same issue? Is there a but in XmlMediaTypeFormatter perhaps?

Thanks
Z...

Coordinator
May 14, 2012 at 9:03 PM

The issue is probably with the XmlSerializer. Can you try configuring the XML formatter to use the DataContractSerializer instead?

Daniel Roth

May 14, 2012 at 10:46 PM

Hi

When I set it to use DataContractSerializer, I do get the value now but in two separate sub-nodes...

GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseDataContractSerializer = true;

For example I get:

 
<DateSold xmlns:a="http://schemas.datacontract.org/2004/07/System">
  <a:DateTime>2011-06-09T15:28:35.280891Z</a:DateTime>
  <a:OffsetMinutes>-240</a:OffsetMinutes>
</DateSold>
What I am expecting is ISO 8601 string (which JsonFormatter does return) like so:
<DateSold>2011-06-09T11:28:35.280891-04:00</DateSold>
Is this a bug in Xml Formatter?
Coordinator
May 15, 2012 at 12:36 AM

That’s just how the DataContractSerializer serializes DateTimeOffsets. It’s not a bug.

If you want to do something different I think your only option is to write an IXmlSerializable wrapper around DateTimeOffset.

Daniel Roth

May 15, 2012 at 5:21 PM

But why is it not working by default? Meaning when DataContractSerializer is not used?

If DataContractSerializer is not used in XmlFormatter, should the output match that of JsonSerialized? In this case single xml node as stated above...

Coordinator
May 15, 2012 at 5:52 PM

Sadly our XML serialization story in .NET is not all it should be. Json.NET has a flexible converter story that gives you great control over how types like DateTimeOffset. The XML serializers in .NET just don’t have the same level of flexibility.

We are switching to use the DataContractSerializer by default, so that you at least get a reasonable consistent programming model for JSON and XML (based on Data Contracts), but there are still functional gaps between the two.

Daniel Roth

May 15, 2012 at 6:19 PM
Edited May 15, 2012 at 6:19 PM

I see....Thanks for the explanation.

You are correct in regards to Json.NET - I am using custom JsonNetCamelCaseFormatter for json output

I am even considering creating a custom Xml formatter that would use JsonConvert.DeserializeXmlNode( ) - perhaps I would get a consistent output...But then the binders may not work...Have not tried it:) Since I have luxury of using only Json I can remove xml formatter for now or just leave it as it using DataContractSerializer...

 

Again thanks for the explanation.