Stan
Stan

Reputation: 26501

How to set default serializer to JSON without removing XML serializer

Is it possible to make JSON the default serializer in WebApi2 without removing the XML one?

I've tried to order XmlSerializer to back and JsonSerializer to front but nothing seems to change.

Upvotes: 0

Views: 134

Answers (1)

Yishai Galatzer
Yishai Galatzer

Reputation: 8862

By default the json formatter should "win". There are a few things determining what formatter is going to "win".

  1. Can the JSON formatter even write your type, you might want to verify that first. If you use a DataContractSerializer it's a bit more picky, the json.net version is behaving nicer (and it's default).
  2. If you have no AcceptHeader, the content negotiator still looks at the content type of the request and will prefer that. Is your request sending XML?

If both of these questions are not the issue, the content negotiator (DefaultContentNegotiator) will now end up with the XML and the JSON formatters and call SelectResponseMediaTypeFormatter

Here basically it will pick the first formatter on the list (I'm saying it with a caviat as it's a bit more complex than that) so you want to verify your list is actually re-ordered as you expected it.

Lastly and I don't think you need to get there as the stuff above should get you fixed, you can always replace the IContentNegotiator and override SelectResponseMediaTypeFormatter where if you have more than one formatter you choose the Json one.

Upvotes: 1

Related Questions