0

I've just switched to using the new web api for MVC 4, and I am having great difficulty in deserializing the response from my webservice.

This is my server code:

IEnumerable<Fish> myList = GetFish();

return Request.CreateResponse(HttpStatusCode.OK, myList,"application/xml");

This is serialised as:

<ArrayOfFish xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.datacontract.org/2004/07/MySolution.NameSpace.Resources\" />

As there are no results returned.

When I try to parse this using the XmlMediaTypeFormatter, I get an error saying it wasn't expecting what it got.

My code to deserialise it hasn't changed from before I started using web api, and is simply:

return content.ReadAsAsync<T>(formatters).Result;

formatters is a List of formatters, containing only the XmlMediaTypeFormatter

T is a generic list of Fish

If I omit the "application/xml" type then it appears to send in JSon (as the result is []) however the client expects xml, and will not use a JSon serialiser on it for some reason, even if I explicitly put the type as text/json.

It should be fairly simple to deserialise objects as it's exactly what I was doing before, I've just changed my server very slightly to use CreateResponse to make a HttpResponseMessage instead of using HttpResponseMessage<T> directly, because the generic version isn't supported anymore. I can't find a single client/server example online of someone decoding the result into objects which is frustrating.

Any ideas?

j0k
  • 22,600
  • 28
  • 79
  • 90
NibblyPig
  • 51,118
  • 72
  • 200
  • 356

2 Answers2

0

An XmlSerializer can't serialize an interface (IEnumerable). Convert to a List before returning.

return Request.CreateResponse(HttpStatusCode.OK, myList.ToList(),"application/xml");

simlar question with references here - XmlSerializer won't serialize IEnumerable

Community
  • 1
  • 1
viperguynaz
  • 12,044
  • 4
  • 30
  • 41
0

I ended up discovering that the serialization method web api uses is very slightly different to the former, standard way. I added this to my global.asax and it resolved the issue:

GlobalConfiguration.Configuration.Formatters.Insert(0, new XmlMediaTypeFormatter() { UseXmlSerializer = true });

NibblyPig
  • 51,118
  • 72
  • 200
  • 356