dotnet type_error ai_generated true

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

Also available as: JSON · Markdown · 中文
90%Fix Rate
85%Confidence
1Evidence
2023-06-20First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
System.Text.Json 6.0.x active
System.Text.Json 7.0.x active
System.Text.Json 8.0.x active

Root Cause

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.

generic

中文

System.Text.Json 反序列化失败,因为 JSON 属性类型不匹配(例如数字而非字符串)或缺失,通常由模型属性不匹配(如 JsonIgnore)引起。

Official Documentation

https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/how-to?pivots=dotnet-8-0

Workarounds

  1. 85% success Add a custom JsonConverter to handle type conversion, e.g., convert number to string.
    Add a custom JsonConverter to handle type conversion, e.g., convert number to string.
  2. 90% success Use JsonSerializerOptions.Converters to register converter globally.
    Use JsonSerializerOptions.Converters to register converter globally.
  3. 70% success Change the C# model property type to object or JsonElement and handle casting manually.
    Change the C# model property type to object or JsonElement and handle casting manually.

中文步骤

  1. Add a custom JsonConverter to handle type conversion, e.g., convert number to string.
  2. Use JsonSerializerOptions.Converters to register converter globally.
  3. Change the C# model property type to object or JsonElement and handle casting manually.

Dead Ends

Common approaches that don't work:

  1. 95% fail

    Adding JsonSerializerOptions.IgnoreNullValues doesn't fix type mismatches.

  2. 80% fail

    Changing the JSON source to match the C# model is often not feasible in production.

  3. 90% fail

    Using JsonSerializerOptions.PropertyNameCaseInsensitive only helps with casing, not types.