System.Text.Json not behaving as Newtonsoft when deserializing numbers as strings with spaces
- Dominant language
- C#
- Stars
- 18.3k
- Forks
- 5.6k
- PR merge metrics
- PR metrics pending
Description
### Description
I have searched but could not find this exact issue mentioned.
We migrated from Newtonsoft to System.Text.Json a while back, and since then we have seen bugs with failed requests. This has turned out to be whitespace characters from user input, when inputting numbers. Yes, we should validate this in frontend, but that has not been prioritized, as it worked fine.
### Reproduction Steps
Run this dotnetfiddle (sorry for lazy naming):
```c#
using System;
public class Program
{
public static void Main()
{
var options = new System.Text.Json.JsonSerializerOptions();
options.NumberHandling = System.Text.Json.Serialization.JsonNumberHandling.AllowReadingFromString;
var s = "5 ";
var number = System.Text.Json.JsonSerializer.Deserialize(s, options);
Console.WriteLine(s);
var s2 = """
{
"P": "something",
"I": "4 "
}
""";
var t = Newtonsoft.Json.JsonConvert.DeserializeObject(s2);
Console.WriteLine(t.I);
var t2 = System.Text.Json.JsonSerializer.Deserialize(s2, options);
Console.WriteLine(t2.I);
}
class Test
{
public string P {get;set;}
public int I {get;set;}
}
}
```
### Expected behavior
The newtonsoft deserialization works, but not the S.T.J. when deserializing the object.
### Actual behavior
It fails with
```
Unhandled exception. System.Text.Json.JsonException: The JSON value could not be converted to System.Int32. Path: $.I | LineNumber: 2 | BytePositionInLine: 10.
---> System.FormatException: Either the JSON value is not in a supported format, or is out of bounds for an Int32.
at System.Text.Json.ThrowHelper.ThrowFormatException(NumericType numericType)
```
### Regression?
It works with newtonsoft
### Known Workarounds
Implement manual JsonConverter.
### Configuration
_No response_
### Other information
_No response_
Contributor guide
Assessment
This issue has not been assessed yet.