-
Notifications
You must be signed in to change notification settings - Fork 6k
Description
Deserializing JSON string into a char is now more strict to match user expectations
JsonSerializer.Deserialize<char>(payload)
the payload
must contain a single-character string for deserialization to succeed.
Related to dotnet/runtime#528 (comment)
Version introduced
5.0
Old behavior
When deserializing a char with JsonSerializer if payload consists multicharacter string first character was deserialized.
public static void TestDeserializeToChar()
{
// Before (3.1): Returns the first character - 'a'
JsonSerializer.Deserialize<char>("\"abc\"");
}
New behavior
When deserializing a char with JsonSerializer payload must contain a single-character string for deserialization to succeed, throws JsonException otherwise.
public static void TestDeserializeToChar()
{
// After (5.0): throw JsonException because payload has more than one character
JsonSerializer.Deserialize<char>("\"abc\"");
}
Reason for change
JsonSerializer.Deserialize<TValue>("payload")
parses the text representing a single JSON value into an instance of the type specified by a generic type parameter. Parsing should only succeed when the provided payload
is valid for the specified generic type parameter. For char value type a valid payload is expected to be a single character string.
Recommended action
When parsing a string to a char type using JsonSerializer.Deserialize<char>(payload)
make sure the payload
is non-null, non-empty, and contain a single-character string for a successful deserialization.
Category
- ASP.NET Core
- C#
- Code analysis
- Core .NET libraries
- Cryptography
- Data
- Debugger
- Deployment
- Globalization
- Interop
- JIT
- LINQ
- Managed Extensibility Framework (MEF)
- MSBuild
- Networking
- Printing
- Security
- Serialization
- Visual Basic
- Windows Forms
- Windows Presentation Foundation (WPF)
- XML, XSLT
Affected APIs
System.Text.Json.JsonSerializer.Deserialize(String, JsonSerializerOptions)
Issue metadata
- Issue type: breaking-change