The JSON value could not be converted to System.Boolean--状态字段前后端类型不一致报错

前端代码对status状态的类型一定要遵循后端实体的类型,如果后端实体对状态字段定义为bool, 前端就不能用0和1,用了会造成后端接口验证数据类型就失败报错,连后端的控制器都进不了。具体报错为:The JSON value could not be converted to System.Boolean. Path: $.send_status | LineNumber: 0 | BytePositionInLine: 111.

我在解决这个问题的时候后端用的abpvnext框架,带有swaager,一度以为是swagger验证,但是同事说在做mvc项目的时候他就碰到过类似的前端提交的数据在验证字段类型无法通过的问题,好像是EF的验证。

crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100] Unhandled exception rendering component: An exception occurred executing JS interop: The JSON value could not be converted to System.Boolean. Path: $ | LineNumber: 0 | BytePositionInLine: 4.. See InnerException for more details. Microsoft.JSInterop.JSException: An exception occurred executing JS interop: The JSON value could not be converted to System.Boolean. Path: $ | LineNumber: 0 | BytePositionInLine: 4.. See InnerException for more details. ---> System.Text.Json.JsonException: The JSON value could not be converted to System.Boolean. Path: $ | LineNumber: 0 | BytePositionInLine: 4. ---> System.InvalidOperationException: Cannot get the value of a token type 'Null' as a boolean. at System.Text.Json.ThrowHelper.ThrowInvalidOperationException_ExpectedBoolean(JsonTokenType tokenType) at System.Text.Json.Utf8JsonReader.GetBoolean() at System.Text.Json.Serialization.Converters.BooleanConverter.Read(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options) at System.Text.Json.Serialization.JsonConverter`1[[System.Boolean, System.Private.CoreLib, Version=8.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, Boolean& value, Boolean& isPopulatedValue) at System.Text.Json.Serialization.JsonConverter`1[[System.Boolean, System.Private.CoreLib, Version=8.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state) --- End of inner exception stack trace --- at System.Text.Json.ThrowHelper.ReThrowWithPath(ReadStack& state, Utf8JsonReader& reader, Exception ex) at System.Text.Json.Serialization.JsonConverter`1[[System.Boolean, System.Private.CoreLib, Version=8.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state) at System.Text.Json.Serialization.Metadata.JsonTypeInfo`1[[System.Boolean, System.Private.CoreLib, Version=8.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].Deserialize(Utf8JsonReader& reader, ReadStack& state) at System.Text.Json.Serialization.Metadata.JsonTypeInfo`1[[System.Boolean, System.Private.CoreLib, Version=8.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].DeserializeAsObject(Utf8JsonReader& reader, ReadStack& state) at System.Text.Json.JsonSerializer.ReadAsObject(Utf8JsonReader& reader, JsonTypeInfo jsonTypeInfo) at System.Text.Json.JsonSerializer.Deserialize(Utf8JsonReader& reader, Type returnType, JsonSerializerOptions options) at Microsoft.JSInterop.JSRuntime.EndInvokeJS(Int64 taskId, Boolean succeeded, Utf8JsonReader& jsonReader) --- End of inner exception stack trace --- at Microsoft.JSInterop.JSRuntime.<InvokeAsync>d__16`1[[System.Boolean, System.Private.CoreLib, Version=8.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].MoveNext() at BlazorApp2.Pages.Home.SendReport() in D:\02VSProgram\c#\del\BlazorApp2\Pages\Home.razor:line 109 at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task) at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)
最新发布
10-28
.NET Core 中进行 JSON 反序列化时,如果出现类似 `The JSON value could not be converted to System.String` 的错误,说明反序列化过程中某个字段JSON 值与目标类型(这里是 `string`)兼容。为了定位具体是哪个字段导致了该问题,可以采取以下方法: ### 使用 `ModelState` 查看错误字段 在控制器中,可以通过检查 `ModelState` 来获取详细的绑定错误信息。例如: ```csharp if (!ModelState.IsValid) { foreach (var state in ModelState) { foreach (var error in state.Value.Errors) { Console.WriteLine($"Field: {state.Key}, Error: {error.ErrorMessage}"); } } } ``` 此方法可以输出具体字段名称和错误信息,帮助识别是哪个字段无法正确转换为 `string` 类型[^3]。 ### 检查 JSON 请求内容与 DTO 定义是否匹配 确保请求中的 JSON 字段类型与 DTO 中的属性类型一致。例如,如果 DTO 中某个字段定义为 `string`,但请求中传入的是数字或布尔值,就会导致反序列化失败: ```json { "name": 123 // 此字段应为字符串类型 } ``` 对应的 DTO 应为: ```csharp public class MyDto { public string Name { get; set; } } ``` 这种情况下,反序列化器无法将 `123` 转换为字符串类型,从而抛出异常。 ### 使用 `System.Text.Json` 的详细错误信息 如果使用的是 .NET Core 3.0 及以上版本默认的 `System.Text.Json`,错误信息中通常会包含路径信息,例如: ``` Path: $.name | LineNumber: 5 | BytePositionInLine: 10 ``` 其中 `$.name` 表示 JSON 中的字段路径,可以用于定位具体字段。 ### 替换为 `Newtonsoft.Json` 提升兼容性 若希望获得更灵活的类型转换能力,可以替换默认的 JSON 序列化器为 `Newtonsoft.Json`。安装 `Microsoft.AspNetCore.Mvc.NewtonsoftJson` 包,并在 `Startup.cs` 中注册: ```csharp services.AddControllers().AddNewtonsoftJson(); ``` `Newtonsoft.Json` 在处理类型匹配时通常更具容错性,可以自动进行某些类型转换(如将数字转换为字符串),从而减少此类错误的发生[^1]。 ### 自定义类型转换逻辑 对于需要特殊处理的字段,可以自定义 JSON 转换器。例如,定义一个将任意类型转换为字符串的转换器: ```csharp public class StringConverter : JsonConverter<string> { public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return reader.TokenType switch { JsonTokenType.String => reader.GetString(), JsonTokenType.Number => reader.GetInt32().ToString(), JsonTokenType.True => "true", JsonTokenType.False => "false", _ => throw new JsonException("Unsupported type") }; } public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) { writer.WriteStringValue(value); } } ``` 然后在反序列化时使用该转换器: ```csharp var options = new JsonSerializerOptions(); options.Converters.Add(new StringConverter()); var dto = JsonSerializer.Deserialize<MyDto>(json, options); ``` 该方法可以灵活处理字段类型匹配的问题。 --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值