In .Net Core 3.1 and using System.Text.Json
library, I'm facing an issue that didn't occur in Newtonsoft library.
If I send an empty string in JSON for some properties of type (type in backend) DateTime?
or int?
, it returns 400 status code with an error message that value can't be deserialized. However, with Newtonsoft an empty string is automatically interpreted as a null value for any Nullable<T>.
A minimal example would be:
var json = "\"\"";
Assert.AreEqual(null, Newtonsoft.Json.JsonConvert.DeserializeObject<DateTime?>(json)); // Passes
Assert.AreEqual(null, System.Text.Json.JsonSerializer.Deserialize<DateTime?>(json)); // Throws System.Text.Json.JsonException: The JSON value could not be converted to System.Nullable`1[System.DateTime].
Is there any way to make System.Text.Json
behave in the same way? Demo here.
DateTime
type, but I read someone faced the same issue forInt
type, and maybe for other types, but I don't want to wait till I face the same issues for all types and create custom converter for each one. – Spank