JSON.NET序列化程序将字符串不正确地序列化为布尔值 [英] JSON.NET serializer improperly serializes string as boolean

查看:69
本文介绍了JSON.NET序列化程序将字符串不正确地序列化为布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堂课

[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
        };
    }
}

和一个控制器,例如:

public HttpResponseMessage Post(int caseid, Guid id, UserPreferenceDTO prefs)
{ ... }

注意 :控制器类装饰有[CamelCaseControllerConfig]属性 这样做:

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" }

value通常是一个JS布尔值.问题在于,当到达控制器时,布尔值将转换为C#布尔值(True/False)并进行字符串化.

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.

例如,发送

'{ "name": "wantColFit", "value": "false" }'

成为:

.NET控制器中.

如果查看模型(UserPreferenceDTO)定义,则Value将采用string.那么,为什么序列化程序将值转换为布尔值?

If you look at the model (UserPreferenceDTO) definition Value takes a string. So why is the serializer converting the value into a boolean?

我宁愿将值保存时保存为"true"/"false"(这将使它更容易在客户端上解析回布尔值,因为JSON.parse("true") === trueJSON.parse("True") !== true)

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)

推荐答案

无法弄清楚Json.Net如何(也不为什么)将像"true"这样的字符串反序列化为C#布尔True,所以我只是借用了这个要点: BooleanConverter.js 其中,ReadJson的作用是:

Couldn't figure out how (nor why) Json.Net was deserializing a string like "true" to a C# boolean True so I just borrowed this gist: BooleanConverter.js where ReadJson does:

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var val = reader.Value.ToString().ToLower().Trim();

        if (val == "true" || val == "false")
            return val;

        // If we reach here, we're pretty much going to throw an error so let's let Json.NET throw it's pretty-fied error message.
        return new JsonSerializer().Deserialize(reader, objectType);
    }

并且我能够序列化我的模型一个合适的"true""false"值(而不是"True""False")

and I was able to serialize my model a proper "true" or "false" value (rather than "True" or "False")

如果任何人都可以回答Json.Net在内部进行的操作以转换类似布尔的字符串"true"/"false",我将接受他们的回答.

If anyone can answer what Json.Net is doing internally to cast the boolean-like strings "true"/"false" I will accept their Answer.

这篇关于JSON.NET序列化程序将字符串不正确地序列化为布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆