dotnet
type_error
ai_generated
true
System.Text.Json.JsonException: JSON 值无法转换为 System.String。路径: $.propertyName | 行号: 1 | 字节位置: 20。
System.Text.Json.JsonException: The JSON value could not be converted to System.String. Path: $.propertyName | LineNumber: 1 | BytePositionInLine: 20.
ID: dotnet/serialization-json-ignore-attribute
90%修复率
85%置信度
1证据数
2023-06-20首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| System.Text.Json 6.0.x | active | — | — | — |
| System.Text.Json 7.0.x | active | — | — | — |
| System.Text.Json 8.0.x | active | — | — | — |
根因分析
System.Text.Json 反序列化失败,因为 JSON 属性类型不匹配(例如数字而非字符串)或缺失,通常由模型属性不匹配(如 JsonIgnore)引起。
English
System.Text.Json deserialization fails because a JSON property has an unexpected type (e.g., number instead of string) or is missing, often due to mismatched model attributes like JsonIgnore.
官方文档
https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/how-to?pivots=dotnet-8-0解决方案
-
Add a custom JsonConverter to handle type conversion, e.g., convert number to string.
-
Use JsonSerializerOptions.Converters to register converter globally.
-
Change the C# model property type to object or JsonElement and handle casting manually.
无效尝试
常见但无效的做法:
-
95% 失败
Adding JsonSerializerOptions.IgnoreNullValues doesn't fix type mismatches.
-
80% 失败
Changing the JSON source to match the C# model is often not feasible in production.
-
90% 失败
Using JsonSerializerOptions.PropertyNameCaseInsensitive only helps with casing, not types.