How to set Json.Net as the default serialezer for WCF Rest service

Jun 25, 2010 at 1:31 PM

Is it possible to override the default WCF DataContractSerializer behaviour when Serialize/DeSerialize entities and use JSON.NET instead?

I have the following Service contract for handeling the City entity. For design reasons the City entity has IsReference=true, and therefore the default DataContractSerializer raise errors.

For the "GET" methods I can handle the situation with JsonConvert.DeserializeObject, but with "PUT,POST,DELETE" methods DataContractSerializer takes precedence and fails complaining for the IsReference entities cannot be serializeed. 

I’d appreciate any help or guidance regarding this scenario, or advice to other approaches.

Many thanks

Hossam

 

    [ServiceContract]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class CityService
    {
        [Description("Get all Cities")]  
        [WebGet(UriTemplate = "")]
        public Message Cities()
        {

        }

        [Description("Allows the details of a single City to be updated.")]
        [WebInvoke(UriTemplate = "{code}", Method = "PUT")]
        public Message UpdateCity(string code, City city)
        {
        }
    }
Aug 18, 2010 at 1:56 AM
Did you ever figure this out? I'm stuck on a very similar situation.
Sep 10, 2010 at 6:18 PM

You could consider using RestCake (http://restcake.net) to make your REST services in C#.  The RestCake library uses the same attributes as WCF REST services, so there's very little you have to change.  Just make your service class inherit from RestHttpHandler, and set up a route in your Global.asax, and presto, your service can now be accessed via your new route.  And all of the serialization and deserialization uses Json.NET.

Disclaimer:  I'm the author of the RestCake library, but this isn't just a silly promotion.  I became very frustrated with WCF REST, and it's inability to use alternative serializers, among other shortcomings.  This could be a great solution to your problem, give it a quick read.

Apr 12, 2011 at 8:49 PM

You can check out my post in this thread: http://json.codeplex.com/discussions/209865