title: WCF RESTful web service with JSON.Net: avoid double serialization
body: <p>Long time lurcher, first time poster here.
  I've been grappling with this problem for a few days now and would appreciate any tips.
  I break down the issue here below.</p>
  
  <p><strong>What I'm trying to achieve:</strong><br>
  I want to set up a JSON WCF web service but I want to use the JSON.net serializer instead of the one that comes with WCF. Why? Because I found that serializing using the one that comes with WCF bloats up collections (I will show an example of what I mean below). The end consumer of the service is going to be a JavaScript client, so I don't want to have the client do extra messing around to navigate through the JSON.</p>
  
  <p>I came up with a simple example of what I wanted and set out to try to make it work in C#. I must admit to not having used .NET in a long time, which perhaps contributes to my slowness. Anyway, I've got the patience in stock so on with it.</p>
  
  <p>So, I want a service that accepts a username and returns a JSON object with some info on the user.
  I envisaged the service to be called something like this:</p>
  
  <pre><code>http://someHostName/whoareyou?username=paul
  </code></pre>
  
  <p>And have the service respond with this:</p>
  
  <pre><code>{
      "errorCode": 0,
      "payLoad"  :  {
          "userFullName": "Paul The Octopus",
          "userLevel"        : "Administrator"
      }
  }
  </code></pre>
  
  <p>I could use the above response's JSON object in JavaScript or PHP easily and feel really good about myself.</p>
  
  <p>After some googling around I came across some posts suggesting this would be easy to do with WCF in .NET Framework 4. I had done some fiddling with WCF at a course a while ago but had long forgotten 99% of it so I found and followed this post to adapt to my goal:
  <a href="http://www.codeproject.com/Articles/105273/Create-RESTful-WCF-Service-API-Step-By-Step-Guide#" rel="nofollow">http://www.codeproject.com/Articles/105273/Create-RESTful-WCF-Service-API-Step-By-Step-Guide#</a></p>
  
  <p><strong>Attempt take 1:</strong><br>
  Following the above post I was able to set up a WCF Service (code set out below) that did what I wanted but the resulting JSON output was a bit bloated, as you can see below.  </p>
  
  <p><em>RestServiceImpl.svc.cs file</em>  </p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Runtime.Serialization;
  using System.ServiceModel;
  using System.Text;
  using Newtonsoft.Json;
  using System.Collections.Specialized;
  //Based on this psot: http://www.codeproject.com/Articles/105273/Create-RESTful-WCF-Service-API-Step-By-Step-Guide
  
  namespace RestService
  {
      public class RestServiceImpl : IRestServiceImpl
      {
          #region IRestService Members
  
          public WhoAreYouResponse whoareyou(string username)
          {
              var payLoad = new Dictionary&lt;string, string&gt;
              {
                  {"userFullName", "Paul The Octopus"},
                  {"userLevel", "Administrator"}
              };
  
              WhoAreYouResponse whoAreYouResponse = new WhoAreYouResponse
              {
                  errorCode = 0,
                  payLoad   = payLoad
              };
  
              return whoAreYouResponse;
          }
  
          #endregion
      }
  
      //Helper bits to be used in service implementation
      public class WhoAreYouResponse
      {
          public int errorCode { get; set; }
          public Dictionary&lt;string,string&gt; payLoad { get; set; }
      }
  }
  </code></pre>
  
  <p><em>IRestServiceImpl.cs file</em>  </p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Runtime.Serialization;
  using System.ServiceModel;
  using System.ServiceModel.Web;
  using System.Text;
  
  namespace RestService
  {
      [ServiceContract]
      public interface IRestServiceImpl
      {
          [OperationContract]
          [WebInvoke(Method = "GET", 
              ResponseFormat = WebMessageFormat.Json, 
              BodyStyle = WebMessageBodyStyle.Bare, 
              UriTemplate = "json/whoareyou?username={username}")]
          WhoAreYouResponse whoareyou(string username);
      }
  }
  </code></pre>
  
  <p><em>Web.config file</em>  </p>
  
  <pre><code>&lt;?xml version="1.0"?&gt;
  &lt;configuration&gt;
  
    &lt;system.web&gt;
      &lt;compilation debug="true" targetFramework="4.0" /&gt;
    &lt;/system.web&gt;
    &lt;system.serviceModel&gt;
      &lt;services&gt;
        &lt;service name="RestService.RestServiceImpl" behaviorConfiguration="ServiceBehavior"&gt;
          &lt;endpoint address="" binding="webHttpBinding" contract="RestService.IRestServiceImpl" behaviorConfiguration="web"&gt;
          &lt;/endpoint&gt;
        &lt;/service&gt;
      &lt;/services&gt;
      &lt;behaviors&gt;
        &lt;serviceBehaviors&gt;
          &lt;behavior name="ServiceBehavior"&gt;
            &lt;!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment --&gt;
            &lt;serviceMetadata httpGetEnabled="true"/&gt;
            &lt;!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information --&gt;
            &lt;serviceDebug includeExceptionDetailInFaults="false"/&gt;
          &lt;/behavior&gt;
        &lt;/serviceBehaviors&gt;
        &lt;endpointBehaviors&gt;
          &lt;behavior name="web"&gt;
            &lt;webHttp/&gt;
          &lt;/behavior&gt;
        &lt;/endpointBehaviors&gt;
      &lt;/behaviors&gt;
      &lt;serviceHostingEnvironment multipleSiteBindingsEnabled="true" /&gt;
    &lt;/system.serviceModel&gt;
   &lt;system.webServer&gt;
      &lt;modules runAllManagedModulesForAllRequests="true"/&gt;
    &lt;/system.webServer&gt;
  
  &lt;/configuration&gt;
  </code></pre>
  
  <p>*Result of calling the service through a browser like this <code>http://192.168.0.84/TestRestService/RestServiceImpl.svc/json/whoareyou?username=paul*</code>  </p>
  
  <pre><code>{
      "errorCode":0,
      "payLoad"   : [
          {"Key":"userFullName", "Value":"Paul The Octopus"},
          {"Key":"userLevel","Value":"Administrator"}
      ]
  }
  </code></pre>
  
  <p>The hair in the soup in the JSON response is the way the Dictionary object has been mapped out in the JSON response to "payLoad". It's an array of objects, whereas I was expecting a JSON object sans this "Key", "Value" business. Not quite what I wanted. Close, but pretty finicky to handle at the client end. No one likes bloat and unnecessary work, so thumbs down to this.</p>
  
  <p>Doing some more trolling around for solutions I read some SO posts suggesting what's happening here is that the service is using the built-in serializer
  and that doesn't serialize "dictionaries in any other way". Some extra work would be needed to get it in the format I was expecting.
  So, I thought, how about using another serializer?
  Following this thought I found out about this bad boy here: <a href="http://james.newtonking.com/projects/json-net.aspx" rel="nofollow">http://james.newtonking.com/projects/json-net.aspx</a></p>
  
  <p>This lead to my second attempt below.</p>
  
  <p><strong>Attempt take 2:</strong><br>
  Downloading and importing the JSON.NET serializer into my little project, I altered the following files to look like this (changing the return type of the <em>whoareyou</em> method to <em>string</em>):</p>
  
  <p><em>RestServiceImpl.svc.cs</em>  </p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Runtime.Serialization;
  using System.ServiceModel;
  using System.Text;
  using Newtonsoft.Json;
  using System.Collections.Specialized;
  //Based on this psot: http://www.codeproject.com/Articles/105273/Create-RESTful-WCF-Service-API-Step-By-Step-Guide
  
  namespace RestService
  {
      public class RestServiceImpl : IRestServiceImpl
      {
          #region IRestService Members
  
          public string whoareyou(string username)
          {
              var payLoad = new Dictionary&lt;string, string&gt;
              {
                  {"userFullName", "Paul The Octopus"},
                  {"userLevel", "Administrator"}
              };
  
              WhoAreYouResponse whoAreYouResponse = new WhoAreYouResponse
              {
                  errorCode = 0,
                  payLoad   = payLoad
              };
  
              return JsonConvert.SerializeObject(whoAreYouResponse);
          }
  
          #endregion
      }
  
      //Helper bits to be used in service implementation
      public class WhoAreYouResponse
      {
          public int errorCode { get; set; }
          public Dictionary&lt;string,string&gt; payLoad { get; set; }
      }
  }
  </code></pre>
  
  <p><em>IRestServiceImpl.cs</em>  </p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Runtime.Serialization;
  using System.ServiceModel;
  using System.ServiceModel.Web;
  using System.Text;
  
  namespace RestService
  {
      [ServiceContract]
      public interface IRestServiceImpl
      {
          [OperationContract]
          [WebInvoke(Method = "GET", 
              ResponseFormat = WebMessageFormat.Json, 
              BodyStyle = WebMessageBodyStyle.Bare, 
              UriTemplate = "json/whoareyou?username={username}")]
          string whoareyou(string username);
      }
  }
  </code></pre>
  
  <p>And when the service is called I get this response:  </p>
  
  <pre><code>"{
  \"errorCode\":0,
  \"payLoad\":{
      \"userFullName\":\"Paul The Octopus\",
      \"userLevel\":\"Administrator\"}
  }"
  </code></pre>
  
  <p>Winner! That's what I wanted and expected….BUT. Back the truck up. The entire JSON object is enclosed in double quotes!?
  Hmmm. This is a string containing a JSON object. I took the hair out of the soup and now a fly's flown into it!</p>
  
  <p>After a moment's head scratching it became obvious (I think) that what's happening is that the JSON.NET serializer is working like a charm, spitting out a JSON object in a string, but that is then put through the WCF serializer and is essentially stringified. So what I see in the return is a JSON string. So close! In fact, my method <em>whoareyou</em> says that it returns a string, so pretty much my fault.</p>
  
  <p>So, my question is, how do I get this problem child to stop this double-serialization business? I can't find a return type for my <em>whoareyou</em> method to be something like JSON object.
  Is there a way of telling WCF to use the JSON.NET serializer instead, or some such solution?</p>
  
  <p>Pointers much appreciated.</p>