Skip to content
This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
/ corefx Public archive

[release/3.1] Do not null ref or throw index out of range exception when deserializing to char. #42869

Merged
merged 1 commit into from
Mar 25, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,12 @@ internal sealed class JsonConverterChar : JsonConverter<char>
{
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)
Expand Down
5 changes: 5 additions & 0 deletions src/System.Text.Json/src/System/Text/Json/ThrowHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions src/System.Text.Json/tests/Serialization/Null.ReadTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -152,5 +152,16 @@ public static void NullAcceptsLeadingAndTrailingTrivia()
Assert.Null(obj);
}
}

[Fact]
public static void NullReadTestChar()
{
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<char>("null"));
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<char>("\"\""));
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<char>("")); // Empty JSON is invalid
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<char>("1234")); // Can't convert a JSON number to JSON string/char
Assert.Equal('a', JsonSerializer.Deserialize<char>("\"a\""));
Assert.Equal('Y', JsonSerializer.Deserialize<char>("\"\u0059\""));
}
}
}