I have a class:
[JsonObject(MemberSerialization.OptIn)]
public class UserPreferenceDTO
{
[JsonProperty]
public string Name { get; set; }
[JsonProperty]
public string Value { get; set; }
public static explicit operator UserPreferenceDTO(UserPreference pref)
{
if (pref == null) return null;
return new UserPreferenceDTO
{
Name = pref.Name,
Value = pref.Value
};
}
public static explicit operator UserPreference(UserPreferenceDTO pref)
{
if (pref == null) return null;
return new UserPreference
{
Name = pref.Name,
Value = pref.Value
};
}
}
and a controller, eg, :
public HttpResponseMessage Post(int caseid, Guid id, UserPreferenceDTO prefs)
{ ... }
NOTE: The controller class is decorated with a [CamelCaseControllerConfig]
attribute
which does this:
public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor)
{
var formatter = controllerSettings.Formatters.OfType<JsonMediaTypeFormatter>().Single();
controllerSettings.Formatters.Remove(formatter);
formatter = new JsonMediaTypeFormatter
{
SerializerSettings = { ContractResolver = new CamelCasePropertyNamesContractResolver() }
};
controllerSettings.Formatters.Add(formatter);
}
On the client I'm sending over an object like this:
{ name: "name", value: "Some value" }
Often value
is a JS boolean. The problem is that when it reaches the controller, the boolean is converted to a C# boolean (True
/False
) and stringified.
For example, sending
'{ "name": "wantColFit", "value": "false" }'
becomes:
in the .NET controller.
If you look at the model (UserPreferenceDTO
) definition Value
takes a string
. So why is the serializer converting the value into a boolean?
I would much rather have the value be preserved as "true"
/"false"
when it is saved (which would make it easier to parse back to a boolean on the client, since JSON.parse("true") === true
but JSON.parse("True") !== true
)