You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JSON布尔字符串转MVC bool报错,如何将布尔值存为0/1到数据库?

问题描述
  • 接口端点:https://myapi/user/1234
  • 请求体示例:
{
  "ExpiryDays": "50",  
  "Access1": "False",
  "Access2": "True",
  "Access3": "False",
  "Address": "500"
}
  • 数据库字段及类型:
ExpiryDays  int 
Access1     bit, not null
Access2     bit, not null
Access3     bit, not null
Address     nvarchar(max)
  • 问题场景:MVC模型中把Access相关字段定义为bool类型,预期JSON中的字符串"False"/"True"自动转换为数据库的0/1,但出现报错:

The JSON value could not be converted to System.Nullable`1[System.Boolean]. Path: $.Access1 .

解决方法

方法1:自定义JSON转换器

创建自定义布尔类型转换器,处理字符串形式的"True"/"False":

public class StringBoolConverter : JsonConverter<bool>
{
    public override bool Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        if (reader.TokenType == JsonTokenType.String)
        {
            string value = reader.GetString()?.Trim();
            return value.Equals("True", StringComparison.OrdinalIgnoreCase);
        }
        return reader.GetBoolean();
    }

    public override void Write(Utf8JsonWriter writer, bool value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value ? "True" : "False");
    }
}

局部使用(单字段)

在模型的Access字段上标记使用该转换器:

public class UserModel
{
    public int ExpiryDays { get; set; }
    
    [JsonConverter(typeof(StringBoolConverter))]
    public bool Access1 { get; set; }
    
    [JsonConverter(typeof(StringBoolConverter))]
    public bool Access2 { get; set; }
    
    [JsonConverter(typeof(StringBoolConverter))]
    public bool Access3 { get; set; }
    
    public string Address { get; set; }
}

全局使用(所有布尔字段)

在Program.cs中注册全局转换器(适用于.NET Core/.NET 5+):

builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.Converters.Add(new StringBoolConverter());
    });

方法2:模型字段改用字符串,手动转换

把模型中的Access字段定义为string类型,接收值后手动转换为bool再存入数据库:

public class UserModel
{
    public int ExpiryDays { get; set; }
    public string Access1 { get; set; }
    public string Access2 { get; set; }
    public string Access3 { get; set; }
    public string Address { get; set; }

    // 辅助属性供数据库操作使用
    public bool Access1Bool => Access1.Equals("True", StringComparison.OrdinalIgnoreCase);
    public bool Access2Bool => Access2.Equals("True", StringComparison.OrdinalIgnoreCase);
    public bool Access3Bool => Access3.Equals("True", StringComparison.OrdinalIgnoreCase);
}

业务逻辑中直接使用Access1Bool等属性的值写入数据库即可。

方法3:开启Newtonsoft.Json字符串转布尔兼容

如果项目使用Newtonsoft.Json而非System.Text.Json,可直接开启兼容配置:
在Startup.cs中添加:

services.AddControllers()
    .AddNewtonsoftJson(options =>
    {
        options.SerializerSettings.BooleanParseHandling = BooleanParseHandling.AllowString;
    });

该配置会自动将"True"/"False"字符串转换为对应布尔值。

内容的提问来源于stack exchange,提问作者Tracey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 18:25:33