c# - 如何让 Newtonsoft 将 bool 序列化为 false,而不是 False 或 "false"

标签 c# json.net

<分区>

如果我序列化一个 bool 值,我会得到这样的结果:

myboolValue: False

我意识到这是由于 Microsoft 的 ToString() bool 值实现所致。

我可以在 Newtonsoft 中更改设置以输出 false,例如:

myboolValue: false

我可以使用 条件切换到字符串吗? "true": "false",但这会在 JSON 中添加引号,例如:

myboolValue: "false"

自定义序列化程序可以删除引号吗?

最佳答案

Newtonsoft.Json 开箱即用地将 bool 序列化为 true/false:

using System;
using Newtonsoft.Json;

public class Test
{
    public bool f1;
    public bool f2;

    public Test()
    {
        f1 = false;
        f2 = true;
    }
}

class Program
{
    static void Main(string[] args)
    {
        var json = JsonConvert.SerializeObject(new Test());
        Console.WriteLine(json);
    }
}

输出到控制台:

{"f1":false,"f2":true}

此外,您可以使用改进的 JSON bool 转换器,它将 C# bool 写入 true/false 并能够从任何大写/小写的 true/false/yes/no/1/0 字符串值中读取 bool:

/// <summary>
/// Handles converting JSON string values into a C# boolean data type.
/// </summary>
public class BooleanJsonConverter : JsonConverter
{
    #region Overrides of JsonConverter

    /// <summary>
    /// Determines whether this instance can convert the specified object type.
    /// </summary>
    /// <param name="objectType">Type of the object.</param>
    /// <returns>
    /// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
    /// </returns>
    public override bool CanConvert( Type objectType )
    {
        // Handle only boolean types.
        return objectType == typeof(bool);
    }

    /// <summary>
    /// Reads the JSON representation of the object.
    /// </summary>
    /// <param name="reader">The <see cref="T:Newtonsoft.Json.JsonReader"/> to read from.</param>
    /// <param name="objectType">Type of the object.</param>
    /// <param name="existingValue">The existing value of object being read.</param>
    /// <param name="serializer">The calling serializer.</param>
    /// <returns>
    /// The object value.
    /// </returns>
    public override object ReadJson( JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer )
    {
        switch (reader.Value.ToString().ToLower().Trim())
        {
            case "true":
            case "yes":
            case "y":
            case "1":
                return true;
            case "false":
            case "no":
            case "n":
            case "0":
                return false;
        }

        // 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 );
    }

    /// <summary>
    /// Writes the JSON representation of the object.
    /// </summary>
    /// <param name="writer">The <see cref="T:Newtonsoft.Json.JsonWriter"/> to write to.</param><param name="value">The value.</param><param name="serializer">The calling serializer.</param>
    public override void WriteJson( JsonWriter writer, object value, JsonSerializer serializer )
    {
        writer.WriteValue((bool)value);
    }

    #endregion Overrides of JsonConverter
}

要注册此转换器,请使用代码:

JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
    Converters = new List<JsonConverter>
    {
        new BooleanJsonConverter()
    }
}; 

关于c# - 如何让 Newtonsoft 将 bool 序列化为 false,而不是 False 或 "false",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54152416/

相关文章:

binding - 具有不同名称的模型参数的 Web.Api 反序列化失败

c# - Json.net忽略子对象的空值

c# - 如何将缺少的 json 字段反序列化为 null?

c# - 如何在 C# 中使用 Crypt32.dll 以兼容单声道

c# - Get 方法抛出 Request.Path 异常

C#读取文件和编码问题

C# - 解析值 : {. 路径“[0].Statistics”时遇到意外字符

c# - 为多个客户端调用设置 WCF 服务

c# - 压缩大型词典

c# - Json.NET - 如何使用内部构造函数序列化外部类?