You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
The JSON value could not be converted - Model with nullable DateTime #434
... so I'd normally start with squawking at whoever was calling the API incorrectly (Or let them squawk at themselves as it were, since I presume you return a 400 for a failed deserialize).
We can't blanket convert empty to null, since whether empty is valid is up to the individual type deserializers. An attribute like [TreatEmptyAsNull] may be okay, although since callers should normally leave the element off...
But, I think if date is an empty string, it should be treated as NULL or, like you wrote, a little attribute can do the job. What would be the use of a date represented as an empty string?
The problem is that a blank date (or most other objects) would normally be considered invalid on the grounds that, hey, the key was specified, but didn't have a value. Usually you want to stare at your caller because they're probably doing something wrong, which might include not initializing or setting a value they think they are.
I don't think we should allow an empty string to mean null for DateTime by default, because the empty string is not null. Also, other users might depend on the empty string being invalid for these types.
If we do, we'd have to consider the behavior for other types with string format representations: Guid, Uri, TimeSpan etc.
A workaround for your scenario is to use a converter:
usingSystem;usingSystem.ComponentModel.DataAnnotations;usingSystem.Diagnostics;usingSystem.Text.Json;usingSystem.Text.Json.Serialization;publicclassProgram{publicstaticvoidMain(){stringjson=@"{""agreementStartDate"":""2019-12-09T00:00:00.000Z"",""agreementEndDate"":""""}";JsonSerializerOptionsoptions=newJsonSerializerOptions(){PropertyNamingPolicy=JsonNamingPolicy.CamelCase};options.Converters.Add(newCustomJsonConverterForNullableDateTime(options));Managermanager=JsonSerializer.Deserialize<Manager>(json,options);Console.WriteLine(manager.AgreementStartDate);Console.WriteLine(manager.AgreementEndDate==null);}privateclassManager{//...[Required]publicDateTimeAgreementStartDate{get;set;}publicDateTime?AgreementEndDate{get;set;}}privateclassCustomJsonConverterForNullableDateTime:JsonConverter<DateTime?>{publicoverrideDateTime?Read(refUtf8JsonReaderreader,TypetypeToConvert,JsonSerializerOptionsoptions){Console.WriteLine("Reading");Debug.Assert(typeToConvert==typeof(DateTime?));returnreader.GetString()==""?null:reader.GetDateTime();}// This method will be ignored on serialization, and the default typeof(DateTime) converter is used instead.// This is a bug: https://github.com/dotnet/corefx/issues/41070#issuecomment-560949493publicoverridevoidWrite(Utf8JsonWriterwriter,DateTime?value,JsonSerializerOptionsoptions){Console.WriteLine("Here - writing");if(!value.HasValue){writer.WriteStringValue("");}else{writer.WriteStringValue(value.Value);}}}}
I don't think we should allow an empty string to mean null for DateTime by default, because the empty string is not null. Also, other users might depend on the empty string being invalid for these types.
This differs from Newtonsoft's default behavior and would be a breaking change for migrations from Newtonsoft to System.Text.Json. Is that intentional?
Reacted by jasmine-alliswell, erwin-faceit, saxmaster79, Jonathon Fitch, vizak, Jim Love, cricketthomas, David Henley, Andrii Maksymets, Andrew Carney and 5 more
Reacted by Armindo Romario Maurits, cricketthomas, Victor, Nicolas Van Damme and Oğuzhan AZARI
Activity
Clockwork-Muse commentedon Dec 2, 2019
... normally the element should be left out in cases like this:
{ "agreementStartDate": "2019-12-09T00:00:00.000Z" }... so I'd normally start with squawking at whoever was calling the API incorrectly (Or let them squawk at themselves as it were, since I presume you return a 400 for a failed deserialize).
We can't blanket convert empty to null, since whether empty is valid is up to the individual type deserializers. An attribute like
[TreatEmptyAsNull]may be okay, although since callers should normally leave the element off...troncomputers commentedon Dec 2, 2019
@Clockwork-Muse
You are absolutely right. This empty string (probably) came from Angular
FormGroup()that is initialized like that:But, I think if date is an empty string, it should be treated as
NULLor, like you wrote, a little attribute can do the job. What would be the use of a date represented as an empty string?Clockwork-Muse commentedon Dec 2, 2019
The problem is that a blank date (or most other objects) would normally be considered invalid on the grounds that, hey, the key was specified, but didn't have a value. Usually you want to stare at your caller because they're probably doing something wrong, which might include not initializing or setting a value they think they are.
layomia commentedon Dec 3, 2019
I don't think we should allow an empty string to mean
nullfor DateTime by default, because the empty string is notnull. Also, other users might depend on the empty string being invalid for these types.If we do, we'd have to consider the behavior for other types with string format representations: Guid, Uri, TimeSpan etc.
A workaround for your scenario is to use a converter:
If the goal is to ignore empty string values entirely, a future solution with default value handling semantics could be to specify the empty string as a default value for the property (with an attribute), then ignore if null or default (building atop the proposals in https://github.com/dotnet/corefx/issues/40600, https://github.com/dotnet/corefx/issues/38878)
ylibrach commentedon Jan 8, 2020
This differs from Newtonsoft's default behavior and would be a breaking change for migrations from Newtonsoft to System.Text.Json. Is that intentional?
a2kan commentedon Apr 27, 2021
return reader.GetString() == "" ? null : reader.GetDateTime();
In my case this part didn't work for me (if you have a datetime string like this : 2021-04-27 00:00:00)
I changed to
return reader.GetString() == "" ? null : DateTime.Parse(reader.GetString());
eiriktsarpalis commentedon Oct 22, 2021
Closing as by-design behavior. A workaround has been provided in #434 (comment)