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 bool?
, however that takes up at least 2 bytes in memory (see this question), so I wrote my own OptionalBool
struct that only takes up 1 byte and is implicitly convertible to bool?
.
My question is, I have a class like this:
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; }
}
How can I get Json.NET to perform the implcit conversion from OptionalBool
to bool?
while serializing? For example if IncludeUrls
was default(OptionalBool)
(which is 'null'), ReturnDeviceType
was true and ReturnUpdatePromptVersions
was false, then the outputted JSON would look something like
{
"includeUrls": null,
"returnDeviceType": true,
"returnUpdatePromptVersions": false
}
How can I do this given a PartnerLoginOptions
object? The code I have so far is
var body = JsonConvert.SerializeObject(options, new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
edit: In case it's useful, here is the source code for OptionalBool
.