diff --git a/src/System.Text.Json/src/System/Text/Json/Serialization/Converters/JsonValueConverterChar.cs b/src/System.Text.Json/src/System/Text/Json/Serialization/Converters/JsonValueConverterChar.cs index a7e7995f280e..de8b16dbcfcb 100644 --- a/src/System.Text.Json/src/System/Text/Json/Serialization/Converters/JsonValueConverterChar.cs +++ b/src/System.Text.Json/src/System/Text/Json/Serialization/Converters/JsonValueConverterChar.cs @@ -10,7 +10,12 @@ internal sealed class JsonConverterChar : JsonConverter { public override char Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return reader.GetString()[0]; + string str = reader.GetString(); + if (string.IsNullOrEmpty(str)) + { + throw ThrowHelper.GetInvalidOperationException_ExpectedChar(reader.TokenType); + } + return str[0]; } public override void Write(Utf8JsonWriter writer, char value, JsonSerializerOptions options) diff --git a/src/System.Text.Json/src/System/Text/Json/ThrowHelper.cs b/src/System.Text.Json/src/System/Text/Json/ThrowHelper.cs index 553c1c16170f..02252a3c4ca5 100644 --- a/src/System.Text.Json/src/System/Text/Json/ThrowHelper.cs +++ b/src/System.Text.Json/src/System/Text/Json/ThrowHelper.cs @@ -592,6 +592,11 @@ public static FormatException GetFormatException(DataType dateType) ex.Source = ExceptionSourceValueToRethrowAsJsonException; return ex; } + + public static InvalidOperationException GetInvalidOperationException_ExpectedChar(JsonTokenType tokenType) + { + return GetInvalidOperationException("char", tokenType); + } } internal enum ExceptionResource diff --git a/src/System.Text.Json/tests/Serialization/Null.ReadTests.cs b/src/System.Text.Json/tests/Serialization/Null.ReadTests.cs index 4a7daee8fe53..df60dae273b7 100644 --- a/src/System.Text.Json/tests/Serialization/Null.ReadTests.cs +++ b/src/System.Text.Json/tests/Serialization/Null.ReadTests.cs @@ -152,5 +152,16 @@ public static void NullAcceptsLeadingAndTrailingTrivia() Assert.Null(obj); } } + + [Fact] + public static void NullReadTestChar() + { + Assert.Throws(() => JsonSerializer.Deserialize("null")); + Assert.Throws(() => JsonSerializer.Deserialize("\"\"")); + Assert.Throws(() => JsonSerializer.Deserialize("")); // Empty JSON is invalid + Assert.Throws(() => JsonSerializer.Deserialize("1234")); // Can't convert a JSON number to JSON string/char + Assert.Equal('a', JsonSerializer.Deserialize("\"a\"")); + Assert.Equal('Y', JsonSerializer.Deserialize("\"\u0059\"")); + } } }