title: Json.NET: How to perform implicit conversion of an object before serializing?
body: <p>I have a class that has lots of 'optional bools'-- boolean values that may be true, false, or null. The most common way to represent this in .NET is to use <code>bool?</code>, however that takes up at least 2 bytes in memory (see <a href="https://stackoverflow.com/a/294942/4077294">this question</a>), so I wrote my own <code>OptionalBool</code> struct that only takes up 1 byte and is implicitly convertible to <code>bool?</code>.</p>
  
  <p>My question is, I have a class like this:</p>
  
  <pre><code>public class PartnerLoginOptions
  {
      public string Username { get; set; }
      public string Password { get; set; }
      public string DeviceModel { get; set; }
      public string Version { get; set; }
  
      public OptionalBool IncludeUrls { get; set; }
      public OptionalBool ReturnDeviceType { get; set; }
      public OptionalBool ReturnUpdatePromptVersions { get; set; }
  }
  </code></pre>
  
  <p>How can I get Json.NET to perform the implcit conversion from <code>OptionalBool</code> to <code>bool?</code> while serializing? For example if <code>IncludeUrls</code> was <code>default(OptionalBool)</code> (which is 'null'), <code>ReturnDeviceType</code> was true and <code>ReturnUpdatePromptVersions</code> was false, then the outputted JSON would look something like</p>
  
  <pre><code>{
      "includeUrls": null,
      "returnDeviceType": true,
      "returnUpdatePromptVersions": false
  }
  </code></pre>
  
  <p>How can I do this given a <code>PartnerLoginOptions</code> object? The code I have so far is</p>
  
  <pre><code>var body = JsonConvert.SerializeObject(options, new JsonSerializerSettings
  {
      ContractResolver = new CamelCasePropertyNamesContractResolver()
  };
  </code></pre>
  
  <p><strong>edit:</strong> In case it's useful, <a href="https://github.com/jamesqo/Pandorum/blob/master/src/Pandorum.Core.Optional/Core/OptionalBool.cs" rel="nofollow noreferrer">here</a> is the source code for <code>OptionalBool</code>.</p>